Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我怎样才能把这些数字放在列表中?_Python_List_Collatz - Fatal编程技术网

Python 我怎样才能把这些数字放在列表中?

Python 我怎样才能把这些数字放在列表中?,python,list,collatz,Python,List,Collatz,我有一个Collatz猜想赋值。基本上,我必须写一个程序,我给它一个数字,它会为它计算Collatz猜想。但我的问题是:出来的数字会这样写: 12 6 3 10 5 16 8 4 2 1 当它们应该在这样的列表中[12,6,3,10,5,16,8,4,2,1] 这是我的代码: n = int(input("The number is: ")) while n != 1: print(n) if n % 2 == 0: n //= 2 else: n = n *

我有一个Collatz猜想赋值。基本上,我必须写一个程序,我给它一个数字,它会为它计算Collatz猜想。但我的问题是:出来的数字会这样写:

12
6
3
10
5
16
8
4
2
1
当它们应该在这样的列表中[12,6,3,10,5,16,8,4,2,1]

这是我的代码:

n = int(input("The number is: "))
while n != 1:
  print(n)
  if n % 2 == 0:
     n //= 2
  else:
     n = n * 3 + 1
print(1)

你必须把数字存储在一个列表中

result = []
while n != 1: 
      result.append(n) 
      if n % 2 == 0:
          n //= 2
      else:
          n = n * 3 + 1
result.append(n) 

print result

这也是一种选择。一个愚蠢的,但仍然:

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]')

一个递归版本,只是为了好玩:

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)

欢迎用户:UpRe956514:请考虑投票并接受这个答案。