Python, Loop - Do statements until specific answer is given - python

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()))

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))

Automate The Boring Stuff - Collatz Sequence

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')

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.

Collatz Sequence. (Python 3)

I've started the book "Automate The Boring Stuff" by Al Sweigart.
At the end of Chapter 3, the author suggests creating a Collatz Sequence in Python as a practice exercise. (the practice exercise suggests I use a the print function and return statement)
When I use a print() function in my code, it works great and I get all the evaluated values I want to see on the screen:
print("This is The Collatz Sequence")
user = int(input("Enter a number: "))
def collatz(n):
print(n)
while n != 1:
if n % 2 == 0:
n = n // 2
print(n)
else:
n = n * 3 + 1
print(n)
collatz(user)
Question:
How come when I want to use the return statement, the while loop only runs once?
For example, passing the integer 3 into my function with the return statement only gives me the return value of 3 and 10:
print("This is The Collatz Sequence")
user = int(input("Enter a number: "))
def collatz(n):
print(n)
while n != 1:
if n % 2 == 0:
n = n // 2
return n
else:
n = n * 3 + 1
return n
result = collatz(user)
print(result)
return exits the function and, therefore terminates your while loop.
Perhaps you meant to use yield instead:
print("This is The Collatz Sequence")
user = int(input("Enter a number: "))
def collatz(n):
print(n)
while n != 1:
if n % 2 == 0:
n = n // 2
yield(n)
else:
n = n * 3 + 1
yield(n)
print(list(collatz(user)))
Output:
This is The Collatz Sequence
Enter a number: 3
3
[10, 5, 16, 8, 4, 2, 1]
Yield is logically similar to a return but the function is not terminated until a defined return or the end of the function is reached. When the yield statement is executed, the generator function is suspended and the value of the yield expression is returned to the caller. Once the caller finishes (and assumably uses the value that was sent) execution returns to the generator function right after the yield statement.
In your code you don't re-feed the new value back into your equation. Try separating your while loop from the collatz module. I have an example of this below:
def collatz(number):
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1
chosenInt = int(input('Enter an integer greater than 1: '))
print(chosenInt)
while chosenInt != 1:
chosenInt = collatz(chosenInt)
print(chosenInt)
def collatz(number):
if (number%2 == 0):
return print(number//2);
else:
return (print(number*3+1));
inputNumber = input("Enter a number greater than 1:");
result = collatz(int(inputNumber));
while result != 1:
result = collatz(result);
I am getting a typeError with it! Don't know why?

Copy a function in python

I created a function collatz that runs properly. Then based on a list of numbers that I set to be 512 numbers long, should run through the function that many times to add the number of iterations to get to with the loop:
for number in numbers:
collatz(number)
This worked as expected, except that it preempted the iteration within the function. This left me with a list of iterations all reading 0, though the list of numbers populated properly. For reference, the function which I want to copy is:
def collatz(n):
iterations = []
iterations.append(n)
if n == 1 or n < 1:
iterate_num = len(iterations) - 1
all_iterations.append(iterate_num)
elif n % 2 == 0:
even = n / 2
collatz(even)
elif n % 2 != 0:
odd = (3 * n) + 1
collatz(odd)
else:
pass
Is it possible to copy that function a number of times equivalent to the length of the list of numbers to run through each separately?
You should return iterations and extend it with the result of your recursive calls:
def collatz(n):
# Stuff
elif n % 2 == 0:
even = n / 2
iterations.extend(collatz(even))
else:
odd = (3 * n) + 1
iterations.extend(collatz(odd))
return iterations
Another solution would be to pass iterations by reference:
def collatz(n, iterations = None):
if iterations is None:
iterations = []
# Stuff
elif n % 2 == 0:
even = n / 2
collatz(even, iterations)
else:
odd = (3 * n) + 1
collatz(odd, iterations)
Additionally, this construct is unnecessary:
elif n % 2 == 0:
# stuff
elif n % 2 != 0:
# stuff
else:
pass
First off, having an else: than only does pass is unecessary in itself. Additionally, here n % 2 can only either be zero or not zero so the else clause will never be reached.

Categories