Contents
How to make a Collatz program automate the boring stuff?
If not, rebuke and exit try: number = int (input ()) while number != 1: collatz (number) print (number) number = collatz (number) else: print (‘You Win. The number is now 1!’) except ValueError: print (‘Please enter an integer’) This is what I came up with for this practice exercise. It asks for an input Validates whether it’s an integer.
How to automate the boring stuff in Python?
Please apply the naming conventions and indentation rules. Leave space between operators and their operands (example: newNumber=3*number+1 should be written newNumber = 3 * number + 1) Do not borrow ; sysntax into Python. You should remove it.
Do you need a newnumber variable in Collatz?
You don’t need a newNumber variable at all; you can just overwrite the number parameter. def collatz (n): “”” Generate the Collatz sequence, starting from n, until 1 is reached.
What should the Collatz function look like in Python?
To promote code reuse, you should design the collatz () function so that it doesn’t print anything. Functions should either perform computations or I/O, not both. Furthermore, there should be as little “free-floating” code as possible, and the input-prompting loop should be in a function. Ideally, the main body of the program should look like this:
How does the Collatz sequence work in Python?
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. (Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence, you’ll arrive at 1!
If it is, it loops through the collatz sequence until the result is 1 and then you win. 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:
Why is the Collatz sequence called the simplest impossible math problem?
Even mathematicians aren’t sure why. Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”) Remember to convert the return value from input () to an integer with the int () function; otherwise, it will be a string value.