2
dict={}
def recur(n):
counter=1
original=n
while n!=1:
n = n/2 if n % 2 == 0 else 3*n+1
if n in dict:
counter=counter+dict[n]
dict[original]=counter
return counter
counter=counter+1
dict[original]=counter
return counter
for i in range(1,1000000):
recur(i)
print(max(dict.keys(), key=(lambda k: dict[k])))
如何记忆一次调用中使用的所有数字?例如,当我调用recur(13)时,它将只在字典中存储13的值,但不存储用于重复(13)中的40,20,10,5等的值(012)最长Collatz序列 - 记忆 - Python-迭代与递归
另外,我无法产生递归函数,因为我可以计数(通过在函数中添加计数器参数),但是我不能在字典中添加值。
请建议一种方式,以便尽可能多的值存储在内存中,而且函数是递归的?
您是否试图找出达到1的最大步骤? – thefourtheye
是的。究竟。 ,,, –