You could solve this with recursion, methinks. However, your current implementation is buggy:
len[L]
will throw a TypeError
collatz_steps(1)
returns 1
on my machine
collatz_steps(6)
returns nothing on my machine
The biggest problem with your solution is that you assume that L
is the same each recursive call. However, on each step you go down, L
gets reallocated as a new list. Because of this, the most len(L)
will be is 1.
Another problem is that once you call collatz_steps
recursively, you don't return that value. The because you only return a result when n==1
your final value will never propagate back up.
Instead of using recursion, I would suggest using a simple while loop to get the same result:
def collatz_steps(num):
iterations = 0
while num != 1:
iterations += 1
if num % 2 == 0:
num /= 2
else:
num = 3*num + 1
return iterations
# Prints:
# 0
# 8
print(collatz_steps(1))
print(collatz_steps(6))
You could even make the if statement on one line if you wanted:
def collatz_steps(num):
iterations = 0
while num != 1:
iterations += 1
num = 3*num + 1 if num % 2 else n/2
return iterations
As some general style feedback:
- Don't use single letter variable names. They offer little-to-no help defining what they hold. Always err on the side of being too verbose when naming variables.
- Don't use all uppercase letters unless the variable is supposed to be constant. Convention is the only way we can define constants in Python as there is no syntactic way of doing so.
If you really wanted to use recursion, here is a recursive version of collatz_steps
:
def collatz_steps(num, iterations=0):
if num == 1:
return iterations
iterations += 1
return collatz_steps(3*num + 1, iterations) if num % 2
else collatz_steps(n/2, iterations)