简体   繁体   English

使用递归查找嵌套列表的总和

[英]Find sum of nested list using recursion

Find the sum of nested list using recursion使用递归查找嵌套列表的总和

lst = [1,2,[3,4],[5,6]]
def findSum(values,sum,idx):
    if len(values) == idx:
        return sum
    if isinstance(values[idx],list):
       return findSum(values[idx],sum,0)
    else:
        sum = sum + values[idx]
        return findSum(values,sum,idx+1)

print(findSum(lst,0,0))

Output should be 21 but I am getting only 10 last index subarray([5,6]) not getting calculated. Output 应该是21但我只得到10最后一个索引子数组([5,6])没有得到计算。

Can anyone suggest me, what I am doing wrong in the logic?谁能建议我,我在逻辑上做错了什么?

You can recurse through the list as shown below您可以递归遍历列表,如下所示

def recur_sum(lst):
    s = 0
    for x in lst:
        if type(x) == list:
            s += recur_sum(x)
        else:
            s += x
    return s


lst = [1,2,[3,4],[5,6]]
print(recur_sum(lst))

EDIT: The problem with OP's code is, the code is not moving forward after its done processing a sublist and returns from there.编辑: OP 代码的问题是,代码在处理完子列表并从那里返回后没有继续前进。

There are just some good pointers earlier about the origin codes problem, so I am not going to repeat here.关于源代码问题,前面有一些很好的提示,所以我不打算在这里重复。

This is just a simpler approach for this problem, maybe as a reference.这只是解决这个问题的一种更简单的方法,也许可以作为参考。

A = [1, 2, [3, 4], [5,6]]


def sum_lst(A):
    total = 0
    
    for x in A:
        if isinstance(x, list):
            total += sum_lst(x)
        else:
            total += x
            
    return total
    
print(sum_lst(A))      # 21

Just for fun: a recursive approach using reduce .只是为了好玩:使用reduce的递归方法。

A (mathematical) recursion is defined by an initial value and a relationship between a certain terms and its previous ones. (数学)递归由初始值和某些项与其先前项之间的关系定义。 The initial value can be specified by the initializer parameter of reduce and, in this case, it is set to 0 .初始值可以由reduceinitializer参数指定,在这种情况下,它被设置为0 The recursive function can be passed as a parameter to reduce .递归的 function 可以作为参数传递给reduce

Notice:注意:

  • no for -loop is required不需要for循环
  • only two nested level list supported仅支持两个嵌套级别列表
from functools import reduce


def recursive_relationship(i, j):
    if isinstance(j, list):
        if j:
            return recursive_relationship(i+j[0], j[1:])
        else:
            return i
    return i + j


lst = [1,2,[3,4],[5,6], [8]]
#lst = [[1, 2], [1, 2,3], [1]]

print(reduce(recursive_relationship, lst, 0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM