【问题标题】:Longest Collatz Sequence- Memoization- Python- Iterative vs Recursive最长的 Collat​​z 序列 - 记忆 - Python - 迭代与递归
【发布时间】:2016-05-29 12:15:32
【问题描述】:
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 的值存储在 dict 中,而不存储 recur(13) 中使用的 40、20、10、5 等值

另外,我无法生成递归函数,因为我可以计数(通过在函数中添加计数器参数),但我无法在字典中添加值。

请建议一种方法,以便将最大可能值存储在内存中并且该函数是递归的?

【问题讨论】:

  • 您是否试图找出达到 1 的最大步数?

标签: python-3.x dynamic-programming memoization


【解决方案1】:

这是我能想到的编写递归函数的最易读(也很 Python)的方式;它基本上只是阐明了构建序列的规则,就像您向某人解释的那样:

count = {}

def recur(n):
    if n not in count:  # memoize
        if n == 1:
            count[n] = 0  # finished
        else:
            count[n] = recur(n//2 if n % 2 == 0 else 3*n + 1)
        count[n] += 1  # this step
    return count[n]

for i in range(1, 100):
    recur(i)

for item in sorted(count.items()):
    print(item)

使用1 初始化count 缓存将允许优化,但会牺牲将形成规则直接转换为代码:

count = {1: 1}

def recur(n):
    if n not in count:  # memoize
        count[n] = 1 + recur(n//2 if n % 2 == 0 else 3*n + 1)
    return count[n]

【讨论】:

    猜你喜欢
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2016-01-29
    • 2014-07-07
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    相关资源
    最近更新 更多