使用字典中的collatz序列

  • 本文关键字:collatz 序列 字典 python
  • 更新时间 :
  • 英文 :


我对python还很陌生,目前我正在学习字典。我正在尝试编写一个程序,要求用户输入一个数字,然后输出小于或等于用户用最长的Collatz序列输入的数字。

这就是我现在所拥有的,但我不知道为什么它不起作用。


def collatz(number):
segLength = {}
for i in range(1, number + 1):
current = 1
count = 0
while current != 1:
if current % 2 == 0:
current = number / 2
elif current % 2 != 0:
current = (3 * number + 1) 
count += 1
segLength[i] = count
value = list(segLength.values())
key = list(segLength.keys())
x = max(value)
index = value.index(x)
output = key[index]
return output

result = collatz(number)
print = result  

for循环的每次迭代都设置current = 1,因此current != 1将始终为False,并跳过while

看起来你想计算每个数字的拼贴序列,所以我猜你想设置current = i

然后,对于for循环的每一次迭代,current都会有您想要减少到1的数字,并计算它所需的步骤数。为了使这项工作发挥作用,您需要更改:

current = number / 2

(以及elif中相应的3n+1行(到

current = current / 2

因为number总是您在开始时传递给函数的数字,而不是您试图在这个迭代上运行collatz序列的数字

看起来它应该工作否则!

编辑:你也应该调用print,而不是像Barmar所说的那样分配给它。

最新更新