Python Forum
Collatz in Python...pls help
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Collatz in Python...pls help
#1
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))
Reply
#2
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?
Reply
#3
(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?


   
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)
Reply
#4
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I found how many numbers are there in a Collatz Sequence that I found? cananb 2 2,556 Nov-23-2020, 05:15 PM
Last Post: cananb
  Collatz Conjecture Formatting TreasureDragon 2 2,378 Feb-11-2019, 10:39 PM
Last Post: TreasureDragon

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020