【发布时间】:2021-07-20 07:09:00
【问题描述】:
我需要找到解决这个问题的方法。我写了一个代码来计算列表中给定数字的总和,从给定的索引开始。
def recsumlisti(index, alist):
if len(alist) == 0:
return 0
elif index >= len(alist):
return 0
else:
return alist[index] + recsumlisti(index + 1, alist)
这是我拥有的代码。当 index 为正时它工作得很好,但当 index 为负时它会表现不佳。
例如。如果参数是 recsumlisti(index= -1, alist=[1,2,3,4]) 而不是只给出 4 作为输出,则函数会迭代所有索引直到最终索引,即 index == len(alist) 达到并给出总和 4 + 1 + 2 + 3 = 10。 供您参考的测试用例:
{'index': 2, 'alist': [], 'expected': 0},
{'index': 0, 'alist': [1, 2, 3, 4], 'expected': 10},
{'index': -1, 'alist': [1, 2, 3, 4], 'expected': 4},
我需要改进此程序的建议,使其适用于所有指标,包括正面和负面。我试过使用
return alist[index] + recsumlisti(index, alist[(index + 1):]) 切片方法,但它也会抛出错误。
如果我的假设是错误的,请告诉我,即使对于负索引,我的代码也可以。谢谢!
【问题讨论】:
-
如果你的索引是
-1,那么4 + 3 + 2 + 1?