Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to solve the collatz sequence project at the end of ch. 3 from "automate the boring stuff with python"

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You’re never updating number in your function, just printing the next iteration. This produces two problems:

  1. The loop is infinite because number never changes.
  2. You never get past the first iteration, because you pass the same value of number in 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading