Automate The Boring Stuff - Collatz Sequence - python

I'm new to Python and I having issues with my Collatz Sequence project in the Automate the Boring Stuff book. When I run my code it "prints" 2 of each number. I can't figure out why it is duplicating each number. Anyone have any ideas?
Here are the directions to the short project:
Write a function named collatz() that has one parameter named number. If the number is even, then collatz() should print number // 2 and return this value. If the 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.
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(3 * number + 1)
return 3 * number + 1
print('Enter number: ')
try:
x = int(input())
while x != 1:
collatz(x)
x = collatz(x)
except ValueError:
print('Please use whole numbers only')
When I enter the number 3 I get this:
Enter number:
3
10
10
5
5
16
16
8
8
4
4
2
2
1
1

Your issue is on the line:
while x != 1:
collatz(x)
x = collatz(x)
You are calling collatz twice, so it is printing each number twice.

Here is the debugged version:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(3 * number + 1)
return 3 * number + 1
print('Enter number: ')
try:
x = int(input())
while x != 1:
x = collatz(x)
except ValueError:
print('Please use whole numbers only')

Related

Python: Program running fine but skipping over output lines in code

When I run the following code:
def collatz(number):
if number % 2 == 0:
return number // 2
result = number
print(number)
elif number % 2 == 1:
return 3 * number + 1
result = number
print(number)
n = input('Enter a number: ')
while n != 1:
n = collatz(int(n))
the code runs to get the number to 1, but it always seems to skip the lines
result = number
print(number)
because it does not show any output. But when I visualize it, it is running the number to one. Could someone help explain why that is happening? Thanks so much.
You are using a recursive loop that bypasses those two statements.
def collatz(number):
if number % 2 == 0:
return number // 2 <---- exits function here
result = number
print(number)
elif number % 2 == 1:
return 3 * number + 1 <---- exits function here
result = number
print(number)
The same concept applies if you have the following function.
def add(x,y):
return x + y
print(x)
You would never get to the print(x) statement as you are exiting the function before that line of code!
You need to remove the return statement. Return exits the collatz function immediatly.
this is because it returns the value and it doesn't continue after the return, so you could do:
def collatz(number):
if number % 2 == 0:
result = number / 2
print(result)
return result
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
n = input('Enter a number: ')
while n != 1:
n = collatz(int(n))
When a function sees return it ends immediately and outputs the value after the word. So to get the lines to run, they need to be before the word return:
def collatz(number):
if number % 2 == 0:
result = number
print(number)
return number // 2
elif number % 2 == 1:
result = number
print(number)
return 3 * number + 1
n = input('Enter a number: ')
while n != 1:
n = collatz(int(n))

using the calculation number for the next calculation

experts.
I'm trying to define a function (collatz) that:
Asks for a number. If it is even it prints number // 2, if it odd it prints 3 * number + 1. (OK)
The result, whatever it is, must enter a loop until the result is 1. (NOK)
So, i´m not figure out because the result is not used and is in an infinite loop. Any suggestion?
def collatz():
number = int(input('Enter the number: '))
x = number % 2
while number != 1:
if x == 0:
print(f'{number // 2}')
else:
print(f'{3 * number + 1}')
number = number
print(f'{collatz()}')
You need to actually assign the result back to number.
As well:
The divisibility check needs to be in the loop.
The outer print() is not needed.
The f-strings are redundant. print() converts its arguments to string automatically.
def collatz():
number = int(input('Enter the number: '))
while number != 1:
if number % 2 == 0:
number //= 2 # Short for "number = number // 2"
else:
number = 3*number + 1
print(number)
collatz()
Example run:
Enter the number: 3
10
5
16
8
4
2
1

How do I use a Try and Exception to raise an error with a print message in Python?

I'm trying to run a collatz in Python and I'm having trouble taking into account input that isn't an integer. I would like to have a Try and Except to work within my code that considers the user's non-integer input. Please see my code below.
number = int(input("Please enter a number: "))
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(number * 3 + 1)
return number * 3 + 1
while number != 1:
try:
number = collatz(int(number))
except ValueError:
print("Something went wrong, please try again...")
You are not using the try except when you are calling int on the input, which is why it is still erroring. You should use 2 while loops like this:
number = input("Please enter a number: ")
while not number.isdigit():
number = input("Please enter a number again: ")
number = int(number)
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(number * 3 + 1)
return number * 3 + 1
With try-except (in this case don't include the initial stuff in the other solution):
while True:
try:
number = int(input("Please enter a number: "))
break
except:
pass

Automate the boring tasks - exercise - collatz function

Beginner question here.
I have just attempted an exercise from Automate the boring stuff. I've completed the question in the format suggested by first defining a function as below:
"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."
and then using that same function, meeting those minimal constraints, to write a programme that meets the following requirements:
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.
I've managed to generate a sequence of numbers ending with one, following the above rules, but my program prints each number in the sequence three times. Is anyone able to explain why this might be?
Thanks so much for your help
def collatz(number):
if int(number) % 2 == 0:
print(int(number)//2)
return int(number)//2
else:
print(3 * int(number) + 1)
return 3 * int(number) + 1
collatz(5)
print('Enter a number')
entry = input()
while collatz(entry) != 1:
collatz(entry)
entry = collatz(entry)
Your loop should look like this:
entry = input()
while entry != 1:
entry = collatz(entry)
You are calling the function 3 times and you have a print call in the function.
Only call the function once and I would remove the print statements from the collatz method and just print in the calling loop, e.g.:
In []:
def collatz(number):
if number % 2 == 0:
return number//2
return 3*number + 1
entry = int(input("Enter a number: "))
print(entry)
while entry != 1:
entry = collatz(entry)
print(entry)
Out[]:
Enter a number: 10
10
5
16
8
4
2
1
You can try:
def collatz(number):
if number == 0:
return 'Try again with an integer other than 0'
elif number == 1:
return 1
elif number % 2 == 0:
n = number // 2
print(n)
elif number % 2 == 1:
n = 3 * number + 1
print(n)
while n != 1:
n = collatz(n)
return n
return n
The last statement return n in line 15 is optional.

Python, Loop - Do statements until specific answer is given

I am currently a noob learning Python, and I am trying to complete an exercise. The exercise requires me to:
Input an integer.
Depending on whether that integer is odd or even, do a specific calculation and print the answer.
Take the given answer, and repeat specific calculations again until answer is equal to 1.
The code I have so far completes the first 2 actions, but I am struggling to implement the loop which will continue to rerun the calculations until the answer is 1. Here is my code so far:
def collatz(getNumber):
if getNumber % 2 == 0:
print(getNumber // 2)
elif getNumber % 2 == 1:
print(3 * getNumber + 1)
print('Please write a number')
number = collatz(int(input()))
Use a while loop:
def collatz(number):
print(number)
while number != 1:
if number % 2 == 0:
number //= 2
else:
number = number * 3 + 1
print(number)
Alternatively, you could use recursion:
def collatz(number):
print(number)
if number == 1:
return
collatz(number // 2 if number % 2 == 0 else number * 3 + 1)
def collatz(n):
print n
if n == 1:
return
if n % 2 == 0:
n2 = (n / 2)
elif n % 2 == 1:
n2 = (3 * n + 1)
collatz(n2)
print('Please write a number')
number = collatz(int(input()))

Categories