Python Forum

Full Version: Collatz in Python...pls help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Ok so I wrote this up quickly and it SHOULD work but doesn't. Can someone possibly run ME through this. I admit I am struggling a bit with the concept of return vs print(I get it conceptually...but application wise I trip)

c = int(input('enter num: '))

i = 1
while True:
	if c % 2 == 0:
		c = c // 2
		print(i,']', c)
	elif c % 2 == 1:
		c = (3*c+1)//2
		print(i, ']',c)
	elif c == 1:
		print('took',i,'tries')
	i+=1
this is something I took off SO: I played with it a bit and I've commented parts I don't get...
link to SO source: https://stackoverflow.com/questions/3350...ring-stuff
#Can someone run through this with me?
def coll(x):
	i=1
	if c % 2 == 0:
		print(i,'] even',c//2)
		return c//2
	elif c % 2 == 1:
		result = (3*c +1)//2 #idu the change in variable here?  
		print(i, '] odd',result)
		return result 
	i += 1

c = int(input('enter your num: '))
while c != 1:
	c = coll(int(c))
the first module runs and prints out:
a list like:
Output:
enter num: 5 1 ] 8 2 ] 4 3 ] 2 4 ] 1 5 ] 2
What did you expect?
(Dec-31-2017, 06:26 AM)Larz60+ Wrote: [ -> ]the first module runs and prints out:
a list like:
Output:
enter num: 5 1 ] 8 2 ] 4 3 ] 2 4 ] 1 5 ] 2
What did you expect?


[attachment=339]
My screenshot looks nothing like your result..I just ran the code (f5) for int 5.
Now I'm totally confused!!!
(also in the 2nd module my i counter isn't counting!!! WTF)
Your output is the same as Larz60+'s one, you just run the infinite while loop a little bit longer.

Also, the logic of your first program is incorrect. When c is equal to 1, the elif c % 2 == 1: is true and therefore the statement elif c == 1: is never executed.