Python Recursive Function For Collatz Conjecture
I have written the following recursive program to show the number of steps a number goes through in Collatz Conjecture: def cycle_length(n): count = 0 if n == 1: re
Solution 1:
When n
is 1, you need to increment count
by 1 before returning it.
def cycle_length(n):
count =0if n == 1:
return count + 1# or simply return 1
...
But I think your code is syntactically correct if you do not choose to count the zeroth step.
Solution 2:
When you are making count=1, you should not do count+= in the later if, else if statements. Also, it seems to me that you earlier answer already correct. However, if you want to add 1 to it (i.e. counting the step when 1 occurs), just do the following:
defcycle_length(n):
count = 1if n == 1:
return count
if n%2 == 0:
count = (cycle_length(int(n/2)) +1)
elif n%2 != 0:
count = (cycle_length(int(3*n+1)) + 1)
return count
Solution 3:
the Collatz sequence always start in the given number, therefore your base case should be return 1
that being said, you can also calculate it using iteration as python is not very fond of recursion, for example your code cannot calculate 9780657631 or 75128138247 without getting a recursion error
here is the iterative version
def collatz_length(n):
if n<1:
raise ValueError
count =1while n != 1:
if n%2 == 0:
n = n//2else:
n = 3*n+1
count += 1return count
Post a Comment for "Python Recursive Function For Collatz Conjecture"