I'm supposed to write code that shows the collatz conjecture in 3 different ways for an assignment using recursion. If you're not familiar with the idea, the conjecture states that if you take any starting value n you can ultimate get to the value of 1 by dividing n/2 if n is even or multiplying 3n + 1 if n is odd. I'm supposed to show a completed algorithm in 3 ways, forwards, backwards, and in a palindrome fashion.
For example, the value 32 in the forward fashion would show : 32 16 8 4 2 1
The value 32 in the backwards fashion would show 1 2 4 8 16 32
Finally, the palindrome fashion would show 32 16 8 4 2 1 2 4 8 16 32
I have been able to get forwards and backwards completed but the palindrome part is slipping me up. All my efforts have either shown the forward fashion or gotten me stuck in an infinite loop.
*IMPORTANT * Here's the tricky part: I'm not allowed to declare any local or global variables to help me with the problem. I am only allowed to use the original arguments of the Collatz method, loops, and recursion. Does anyone have a solution for this trickster?
def Collatz(number , algorithm):
if number == 1:
print number
return
if algorithm == 'F':
if number % 2 == 1:
print number
Collatz((3*number) + 1, algorithm)
if number % 2 == 0:
print number
Collatz((number/2),algorithm)
if algorithm == 'B':
if number % 2 == 1:
Collatz((3*number) + 1, algorithm)
print number
if number % 2 == 0:
Collatz((number/2),algorithm)
print number
**if( algorithm == 'P'):**
m = input( "Enter a positive integer value: " )
displaymode = '' # initialize to anything not F, B, P
while displaymode not in ['F', 'B', 'P']:
displaymode = raw_input( "Choose a display mode: F=forward, B=backward, P=palindrome: " )
Collatz( m, displaymode )
print