[英]Sum of the numbers in a list starting from the given index, RECURSIVELY
I need to find the solution to this problem.我需要找到解决这个问题的方法。 I wrote a code to calculate the sum of given numbers in a list, starting from given index.
我写了一个代码来计算列表中给定数字的总和,从给定的索引开始。
def recsumlisti(index, alist):
if len(alist) == 0:
return 0
elif index >= len(alist):
return 0
else:
return alist[index] + recsumlisti(index + 1, alist)
Here's the code that I have.这是我拥有的代码。 It works perfectly fine when index is positive, but it misbehaves when the index is negative.
当索引为正时它工作得很好,但当索引为负时它行为不端。
For eg.例如。 if the parameters are recsumlisti(index= -1, alist=[1,2,3,4]) instead of just giving 4 as the output, the function iterates through all the index until the final index ie index == len(alist) is reached and gives out the sum 4 + 1 + 2 + 3 = 10. Test cases for your reference :
如果参数是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},
I need suggestions to improve this program so that it works for all the indices, positive & negative.我需要改进这个程序的建议,以便它适用于所有的指数,积极的和消极的。 I have tried using
return alist[index] + recsumlisti(index, alist[(index + 1):])
slicing method but it throws error, too.我曾尝试使用
return alist[index] + recsumlisti(index, alist[(index + 1):])
切片方法,但它也会引发错误。
Let me know if my assumptions are wrong and the code that I have is alright even for the negative indices.如果我的假设是错误的,并且我拥有的代码即使对于负指数也没有问题,请告诉我。 Thank you!
谢谢!
You could just check if the index is negative and, if it is, convert it to the corresponding positive one:您可以检查索引是否为负数,如果是,则将其转换为相应的正数:
def recsumlisti(index, alist):
if index < 0:
index = index + len(alist)
if len(alist) == 0:
return 0
elif index >= len(alist):
return 0
else:
return alist[index] + recsumlisti(index + 1, alist)
The rest of the code is the same.其余代码相同。 This way the output of recsumListi(-1, [1,2,3,4]) is 4 as expected
这样 recsumListi(-1, [1,2,3,4]) 的输出如预期的那样是 4
You could also add a ternary operator to check to see if index +1 is 0, and set index to len(alist)
to terminate the program if it is您还可以添加一个三元运算符来检查索引 +1 是否为 0,并将索引设置为
len(alist)
以终止程序(如果是)
def recsumlisti(index, alist):
if len(alist) == 0:
return 0
elif index >= len(alist):
return 0
else:
nextIndex = (index + 1, len(alist))[index + 1 == 0]
return alist[index] + recsumlisti(nextIndex, alist)
again the rest of the code stays the same其余的代码再次保持不变
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.