【问题标题】:Sum of the numbers in a list starting from the given index, RECURSIVELY从给定索引开始的列表中数字的总和,递归
【发布时间】: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?

标签: python recursion


【解决方案1】:

您可以只检查索引是否为负数,如果是,则将其转换为相应的正数:

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)

其余代码相同。 这样recsumListi(-1, [1,2,3,4])的输出就是预期的4

【讨论】:

    【解决方案2】:

    您还可以添加一个三元运算符来检查索引+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)
    
    

    其余代码保持不变

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-08
      • 1970-01-01
      • 1970-01-01
      • 2023-01-07
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      相关资源
      最近更新 更多