Python Forum
Collatz in Python...pls help - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Collatz in Python...pls help (/thread-7255.html)



Collatz in Python...pls help - mepyyeti - Dec-31-2017

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/33508034/making-a-collatz-program-automate-the-boring-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))



RE: Collatz in Python...pls help - Larz60+ - Dec-31-2017

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?


RE: Collatz in Python...pls help - mepyyeti - Dec-31-2017

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


RE: Collatz in Python...pls help - squenson - Dec-31-2017

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.