I'm trying to write a collatz program using the guidelines from a project found at the end of chapter 3 of Automate the Boring Stuff with Python. I'm using python 3.4.0. Here's the project outline:
Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is 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.
The output of this program could look something like this: Enter number: 3 10 5 16 8 4 2 1
I am trying to make a function that uses if and elif statements within a while loop. I want the number to print, and then return to the beginning of the loop and reduce itself to one using the collatz sequence, with each instance of a resulting number being printed as it goes through the loop. With my current code, I'm only able to print the first instance of the number, and that number does not go through the loop after that. Here's my code:
#collatz
print("enter a number:")
try:
number = (int(input()))
except ValueError:
print("Please enter a valid INTEGER.")
def collatz(number):
while number != 1:
if number % 2==0:
number = (number//2)
#print(number)
return (print(int(number)))
elif nnumber % 2==1:
number = (3*number+1)
#print(number)
return (print(int(number)))
continue
collatz(number)
I think that this solution may be even simpler for learners than the accepted one:
The result will something like this:
Nuncjo got the solution that works. I tweaked it a little to add try and except statements for error handling.
My 17 lines of code for the same exercise that I have came up with.
i am reading the same course and i made a very long solution (improving it when i learn somethign new). i suggest keeping your collatz program up to date as you progress in the chapters, its good training. mine has string manipulation and saving to a \collatzrecords.txt now!
I solved the core problem by using recursion (a method calls itself):
spam is my list for all the values a number "sees" on its way to 1. as you can see, when the number is even the ethod is called agin with number/2. if the number is even it is called with number*3+1.
modified the number == 1 check a bit. i hope it saves calculating time - im up to 23 000 000 already! (current record is 15 733 191 with 704 steps to get it to 1)
Every solution on this thread is missing one thing: if the user inputs "1" the function should still run the computations of the Collatz sequence. My solution: