How can I put these numbers in list?

user2956514 picture user2956514 · Nov 5, 2013 · Viewed 11.4k times · Source

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)

Answer

thefourtheye picture thefourtheye · Nov 5, 2013

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