【发布时间】:2020-01-17 23:07:27
【问题描述】:
我正在创建一个程序来计算人体金字塔中每个人的体重,假设每个人的体重方便地为 200 磅。我的问题是我的函数中的最后一个“elif”,它引发了错误:TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'。
这需要是我的类的递归函数。
我已经尝试过“return”语句,并且使用“tot =”而不是“tot +=”。
tot = 0.0
def prac(r, c):
global tot
if c > r:
print('Not valid')
elif r == 0 and c >= 0:
print(tot, 'lbs')
elif r > 0 and c == 0:
tot += (200 / (2 ** r))
prac(r - 1, c)
elif r > 0 and c == r:
tot += (200 / (2 ** r))
prac(r - 1, c - 1)
elif r > 0 and r > c > 0:
tot += (200 + (prac(r - 1, c - 1)) + (prac(r - 1, c)))
prac(r == 0, c == 0)
prac(2, 1)
我希望它能计算 prac(2,1) 到 300 lbs , prac(3,1) 到 425 等。
【问题讨论】:
-
总是发布带有完整回溯的整个错误消息。
-
尽量不要在python中使用递归函数。它没有尾递归优化。
标签: python recursion computer-science recursive-query