【问题标题】:Roads Calculation in Python(recursive)Python中的道路计算(递归)
【发布时间】:2015-11-28 03:48:12
【问题描述】:

我需要计算从 n 到 0 的道路数量,但我的代码似乎在某些情况下有效,而在某些情况下则无效。

编辑: 当我尝试执行时:roads(7, 2 ,3) 它显示:

第95行是最后的递归部分

Traceback (most recent call last):
  File "python", line 102, in <module>
  File "python", line 95, in roads
  File "python", line 95, in roads
  File "python", line 95, in roads
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

def jumps(n, j):

    if n == 0:
        return True
    elif n<0:
        return False
    else:
        if n<j:
            return False
        elif n==j:
            return True
        elif n>j:
            if n%j ==0:
                return True
            else:
                return False

def roads(n, short_jump, long_jump, memo=None):

    if memo == None:
        memo = {}

    if n not in memo:
        if n==0:
            memo[n] = 1
            return memo[n]
        elif n<0:
            memo[n] = 0
            return memo[n]
        else:
            sum_hmrm = 0

            a = jumps(n, short_jump)
            b = jumps(n, long_jump)
            c = n-long_jump
            d = n-short_jump

            if a == True:
                sum_hmrm += 1
            if b == True:
                sum_hmrm += 1

            sum_hmrm += (roads(c, short_jump, long_jump, memo) + roads(d, short_jump, long_jump, memo))

            memo[n] = sum_hmrm
            return memo[n]

【问题讨论】:

  • 在哪些情况下它有效和无效?
  • roads(2, 2, 3) 工作 road(7, 2, 3) 不起作用我认为我的问题发生在 (n>long_jump) 但我不知道为什么
  • “不起作用”是什么意思?它会永远运行吗?引发异常?返回错误答案(以及您如何知道正确答案)?
  • 它应该返回一个整数,它显示了我可以从 n 到 0 有多少种方式,但是当 n 足够大时,它会抛出一个错误,它不能将 None 类型添加到整数
  • 如果备忘录起到记忆的作用,那你就错了。在网上查一下。使用装饰器

标签: python recursion memoization


【解决方案1】:

这个问题与你的记忆方式有关。您的代码主体以if n not in memo 为条件。但是,如果不满足该条件,您根本不做任何事情。这意味着,如果您尝试重新计算您已经评估过的值,您将返回 None 而不是缓存的值。

我认为您想删除缩进的return 行,并在函数末尾添加一个不在if 语句内的行:

if n not in memo:
    if n==0:
        memo[n] = 1 # remove return after this line
    elif n<0:
        memo[n] = 0 # and here
    else:
        sum_hmrm = 0

        a = jumps(n, short_jump)
        b = jumps(n, long_jump)
        c = n-long_jump
        d = n-short_jump

        if a == True:
            sum_hmrm += 1
        if b == True:
            sum_hmrm += 1

        sum_hmrm += (roads(c, short_jump, long_jump, memo) + roads(d, short_jump, long_jump, memo))

        memo[n] = sum_hmrm # the one after this line can just be unindented

return memo[n]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 2011-07-23
    • 2022-01-01
    • 2015-01-08
    • 1970-01-01
    相关资源
    最近更新 更多