The Collatz Sequence
Write a function named
collatz()that has one parameter named
numberis even, then
number // 2and return this value. If
numberis odd, then
collatz()should print and return
3 * number + 1.
Then write a program that lets the user type in an integer and that keeps calling
collatz()on that number until the function returns the value 1.
import sys def collatz(number): if number % 2 == 0: # check's if number is even. funNumber = number // 2 return funNumber elif number % 2 == 1: # check's if number is odd. funNumber = 3 * number + 1 return funNumber print('Enter a number:') try: inputNumber = int(input()) # check's if input is an integer. except: print('Enter a number!') # if not an integer program quits. sys.exit() whileNumber = collatz(inputNumber) # first function call while whileNumber != 1: # while loop until function returns 1. print(whileNumber) whileNumber = collatz(whileNumber) if whileNumber == 1: # when number is 1 program ends. print(whileNumber) break
What do you guys think of my solution?
I'm very happy that I did it without cheating - just thinking about the problem and visualising how the code should flow.
I did get stuck on the
whileNumber = collatz(inputNumber). At first, that line of code was inside the
while loop but that just made my entire program freeze. Glad I got it all working.