[英]How can I put these numbers in list?
So I have this Collatz conjecture assignment. 所以我有这个Collatz猜想的分配。 Basically I have to write a program to which I give number and it will calculate Collatz conjecture for it. 基本上我必须编写一个程序,我给它编号,它将计算Collatz猜想。 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]. 当它们应该在这样的列表中[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)
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
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]')
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.