So I made a nooby Collatz Sequence showing program. I am interested in knowing how many times number
was printed by the computer so that I can see how many steps it took for a number to eventually become 1. If you don't know much about the Collatz sequence, run my code...
import sys
def collatz(number):
if number <= 0:
print("Next time, enter an integer greater than 1.")
sys.exit()
while number % 2 == 0:
number = number // 2
print(number)
if number == 1:
sys.exit()
while number % 2 != 0:
number = 3*number 1
print(number)
collatz(number)
print("Enter a number.")
print("Even number is halfed, odd number is multiplied by 3 and 1 is added to the product.")
print("This is called as Collatz sequence.")
print("Watch as your number slowly becomes 1.\nEnter a positive integer:")
try:
collatz(int(input()))
except ValueError:
print("Next time, Enter a positive integer, you dummy...")
CodePudding user response:
One really quick and dirty way to do this, would be to just use an "iterations" argument. Something like this would get your desired result:
import sys
def collatz(number, iterations=0):
if number <= 0:
print("Next time, enter an integer greater than 1.")
sys.exit()
while number % 2 == 0:
number = number // 2
print(number)
iterations = 1
if number == 1:
print(f'This number took {iterations} steps to get to 1')
sys.exit()
while number % 2 != 0:
number = 3*number 1
print(number)
iterations = 1
collatz(number, iterations)
print("Enter a number.")
print("Even number is halfed, odd number is multiplied by 3 and 1 is added to the product.")
print("This is called as Collatz sequence.")
print("Watch as your number slowly becomes 1.\nEnter a positive integer:")
try:
collatz(int(input()))
except ValueError:
print("Next time, Enter a positive integer, you dummy...")
CodePudding user response:
You can also use a global variable steps
. But NewBoard's solution is also good.
import sys
steps = 0
def collatz(number):
global steps
if number <= 0:
print("Next time, enter an integer greater than 1.")
sys.exit()
while number % 2 == 0:
steps = 1
number = number // 2
print(number)
if number == 1:
print(f"Steps: {steps}")
sys.exit()
while number % 2 != 0:
steps = 1
number = 3*number 1
print(number)
collatz(number)
print("Enter a number.")
print("Even number is halfed, odd number is multiplied by 3 and 1 is added to the product.")
print("This is called as Collatz sequence.")
print("Watch as your number slowly becomes 1.\nEnter a positive integer:")
try:
collatz(int(input()))
except ValueError:
print("Next time, Enter a positive integer, you dummy...")