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.
I had a hard time understanding the logic of this exercise. but I don't know what I did wrong to display the error if we have a negative number.
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
while True:
try:
entry = input('enter a positive number: ')
while entry != 1:
entry = collatz(int(entry))
# if we have a negative number
while entry < 1:
break
except ValueError:
print('Error, enter valid number')
def cyclic(number):
if number % 2 == 0:
if number // 2 == 1:
print(1)
else:
print(number//2)
cyclic(number // 2)
else:
print((number * 3) + 1)
cyclic((number * 3) + 1)
print("Enter a number:")
try:
n = int(input())
cyclic(n)
except ValueError:
print("Unvalied value")
The simplest one
My 17 lines of code for the same exercise that I have came up with.
def collatz(number):
""" check if the number is even or odd and performs calculations.
"""
if number % 2 == 0: # even
print(number // 2)
return number //2
elif number % 2 != 0: # odd
result = 3*number+1
print(result)
return result
try:
n = input('Enter number: ') # takes user input
while n !=1: # performs while loop until 'n' becomes 1
n = collatz(int(n)) # passes 'n' to collatz() function until it arrives at '1'
except ValueError:
print('Value Error. Please enter integer.')
You can simply try this
while True:
number=int(input('Enter next positive number or 0 to quit: '))
iteration=0
currentNumber=0
item=1
sumOfNumbers=0
print(number,end=' ')
if(number):
while currentNumber !=1 :
currentNumber=int(number/2) if(number%2==0) else number*3+1
number=currentNumber
iteration +=1; item +=1
sumOfNumbers +=currentNumber
print(currentNumber,end ='\n' if(item %5==0) else ' ')
print('\nIt took ',iteration,'iterations to arrive at 1')
print('The average is ',round((sumOfNumbers/iteration),2))
else :
break
def collatz(number): if(number%2==0): n=number//2 print(n) return n else: ev=3*number+1 print(ev) return ev num1=input("Enter a number: \n") try: num= int(num1) if(num==1): print("Enter an integer greater than 1") elif(num>1): a=collatz(num) while(True): if(a==1): break else: a=collatz(a) else: print("Please, Enter a positive integer to begin the Collatz sequence") except: print("please, Enter an integer")
Try to came up with a solution based on up to chapter Function from automate the boring stuff. If need help related to Collatz Problem, then visit here: http://mathworld.wolfram.com/CollatzProblem.html
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):
def autocollatz(number):
global spam
spam.append(number)
if number % 2 == 0:
autocollatz (int(number/2))
elif number % 2 == 1 and number != 1:
autocollatz(int(number*3+1))
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)