Reputation: 39
So I have this Collatz conjecture assignment. Basically I have to write a program to which I give number and it will calculate Collatz conjecture for it. Here is my problem though: the number that will come out will be written like this :
12
6
3
10
5
16
8
4
2
1
When they should be in list like this [12, 6, 3, 10, 5, 16, 8, 4, 2, 1].
And here is my code:
n = int(input("The number is: "))
while n != 1:
print(n)
if n % 2 == 0:
n //= 2
else:
n = n * 3 + 1
print(1)
Upvotes: 1
Views: 13581
Reputation: 1
A recursive version, just for fun:
number = int(input("the number is: "))
def collatz(n):
if n == 1:
return [n]
elif n % 2 == 0:
return [n] + collatz(n/2)
else:
return [n] + collatz((3*n)+1)
print collatz(number)
Upvotes: 0
Reputation: 172309
This is also an option. A silly one, but still:
n = int(input("The number is: "))
print('[', end='')
while n != 1:
print(n, end=', ')
if n % 2 == 0:
n //= 2
else:
n = n * 3 + 1
print('1]')
Upvotes: 1
Reputation: 239573
You have to store the numbers in a list
result = []
while n != 1:
result.append(n)
if n % 2 == 0:
n //= 2
else:
n = n * 3 + 1
result.append(n)
print result
Upvotes: 2