superstewie - 3 months ago 8

Python Question

Here's a program that is intended to count the length of a Collatz sequence recursively:

`def odd_collatz ( n ):`

return (3 * n) + 1

def even_collatz ( n ):

return int(n / 2)

def collatz_counter ( initialNumber, initialLength ):

length = initialLength

while True:

if initialNumber == 1:

return length

elif initialNumber != 1:

length += 1

if initialNumber % 2 == 0:

collatz_counter(even_collatz(initialNumber), length)

else:

collatz_counter(odd_collatz(initialNumber), length)

print(collatz_counter(13, 1)

The expected answer should be 10. However, the program gets stuck in an infinite loop. At the second to last step of the sequence

`initalNumber`

`collatz_counter`

`even_collatz`

The expected action of the next step would be to run

`collatz_counter`

`initialNumber`

`initialLength`

`collatz_counter`

`length`

What actually happens is that the function evaluates the first if statement, runs the

`return length`

`if initialNumber % 2...`

Any ideas as to why this might be happening?

Answer

You are mixing recursion and looping in a bit of an odd way. The problem is `while True:`

. Because you never return anything from within the loop there is nothing stopping it from going on forever. Your code reaches 1 then just keeps adding to the length. Here is a fixed version.

```
def odd_collatz ( n ):
return (3 * n) + 1
def even_collatz ( n ):
return int(n / 2)
def collatz_counter ( initialNumber, initialLength ):
length = initialLength
if initialNumber == 1:
return length
elif initialNumber != 1:
length += 1
if initialNumber % 2 == 0:
return collatz_counter(even_collatz(initialNumber), length)
else:
return collatz_counter(odd_collatz(initialNumber), length)
print(collatz_counter(13, 1))
```