如何理解特定嵌套列表中的递归?

时间:2014-12-03 17:10:46

标签: python recursion

我一直试图通过递归来改善,作为练习,我尝试创建一个函数,返回以下嵌套列表中所有int元素的 sum :{{1 }}

几个小时后,我放弃了,找到了一个美丽的解决方案,我想在这里理解。

[1, [2, 3, [4], []], [5]]

上述功能运行并打印以下内容:

def lsum(l):
    if type(l) is int:        
        return l
    elif type(l) is list and len(l) > 0:
        print l
        return lsum(l[0]) + lsum(l[1:])
    return 0

问题:我无法理解的是,当我的列表[1, [2, 3, [4], []], [5]] [[2, 3, [4], []], [5]] [2, 3, [4], []] [3, [4], []] [[4], []] [4] [[]] [[5]] [5] 时,函数找到[[]],因为[[5]][[]][0][][[]][1:]

2 个答案:

答案 0 :(得分:3)

此修改可能有助于您了解正在发生的事情:

def lsum(l, depth=0):
    print depth, l
    if type(l) is int:        
        return l
    elif type(l) is list and len(l) > 0:
        return lsum(l[0], depth+1) + lsum(l[1:], depth+1)
    return 0

使用中:

>>> lsum([1, [2, 3, [4], []], [5]])
0 [1, [2, 3, [4], []], [5]]
1 1
1 [[2, 3, [4], []], [5]]
2 [2, 3, [4], []]
3 2
3 [3, [4], []]
4 3
4 [[4], []]
5 [4]
6 4
6 []
5 [[]]
6 []
6 []
2 [[5]]
3 [5]
4 5
4 []
3 []
15

以另一种方式看待它:

0 :  [1, [2, 3, [4], []], [5]]
     /           \         
1 : 1    [[2, 3, [4], []], [5]]
              /              \
2 :     [2, 3, [4], []]     [[5]]
        /        \            | \
3 :    2     [3, [4], []]    [5] []
             /      |        / \
4 :         3   [[4], []]   5  []
                 /     \
5 :            [4]     [[]]    
               / \      /\
6 :           4  []   []  []

此处的每次拆分都在左侧的l[0]和右侧的l[1:]之间。如您所见,找到5的分支与探索[2, 3, [4], []]并找到空列表[]的分支分开。


请注意,例如ininstance(l, int)通常优先于type(l) is int

答案 1 :(得分:0)

您可以进行以下几项修改

def recursive_sum(l):
    if type(l) is int:     # If an int, just return the value
        return l
    elif not l:            # If an empty list, return 0
        return 0
    else:           # recursively call this function, and sum the returned values
        return sum(recursive_sum(i) for i in l)  

测试

>>> a = [1, [2, 3, [4], []], [5]]
>>> recursive_sum(a)
15