At first I didn’t include a while loop and I would have to rerun the program with the value from the previous time (ie it wouldn’t recycle the results back through the loop) So i added the while loop to try and correct that. Now When I run it, it gets stuck in an infinite loop. Brand new trying to figure this stuff out. Thanks in advance.
the instructions for the project are at the bottom of this link
https://automatetheboringstuff.com/2e/chapter3/
def collatz(number):
if number % 2 == 0:
print(number // 2)
elif number % 2 != 0:
print(3 * number + 1)
while number != 1:
collatz(number)
number = int(input('enter a number:') )
collatz(number)
>Solution :
You’re never updating number in your function, just printing the next iteration. This produces two problems:
- The loop is infinite because
numbernever changes. - You never get past the first iteration, because you pass the same value of
numberin the recursion. When you design a recursive algorithm, the parameters in the recursion need to get you closer to the base case, so you can’t just pass the same value that you received.
You don’t need a while loop because the recursion performs the iteration. You just need to change function so it passes the next value when recursing.
def collatz(number):
print(number)
if number == 1:
return
if number % 2 == 0:
collatz(number // 2)
elif number % 2 != 0:
collatz(3 * number + 1)
number = int(input('enter a number:') )
collatz(number)