2

我正在 Python 中制作一个简单的脚本作为评估Ackermann Function的练习。首先脚本要求用户输入,然后尝试计算其余部分。这是代码:

m = int(input('Please input m.\n'))
n = int(input('Please input n.\n'))


def compute(m, n):
    if m == 0:
        print(n + 1)
    elif m > 0 and n == 0:
        compute(m - 1, 1)
    else:
        compute(m - 1, compute(m, n - 1))


compute(m, n)

让我感到困惑的部分是它返回TypeError时,特别是对于compute(m, n) 中我尝试从 n 和 m 中加或减 1 的行。

print(n + 1)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

我知道 Python 将所有输入都作为字符串,这就是为什么我在脚本一开始就使用 int() 专门转换了输入。然而,TypeError 似乎暗示在 compute(m, n) 中,m 和 n 不是 int,而是 NoneType,因此它们不能相加或相减。为什么会这样,我该如何解决?

4

1 回答 1

6

任何富有成效的递归函数都必须有一个或多个 return 语句。参考这个

m = int(input('Please input m.\n'))
n = int(input('Please input n.\n'))

def compute(m, n):
    if m == 0:
        return n + 1
    elif m > 0 and n == 0:
        return compute(m - 1, 1)
    else:
        return compute(m - 1, compute(m, n - 1))


print(compute(m, n))

应该按您的预期工作。

于 2020-03-20T08:04:45.123 回答