简体   繁体   中英

Sum of ints and floats in a multi nested list

def recListSum(lst):
    '''Takes an arbitrarily nested list as a parameter and returns the sum of
the numbers in the list'''
    if len(lst)==0:
        return 0
    if len(lst) > 0:
        val = recListSum(lst[1:])+recListSum(lst[0])
        if type(lst[0]) != list:
            if type(lst[0])==float or type(lst[0])==int:
                return val
        if type(lst[0])==list and len(lst[0])>0:
            val = recListSum(lst[1:])+recListSum(lst[0])
            return val

Based on your comment, it sounds like you are giving the len() function an integer value. Since a number doesn't really have a length, that is going to throw an error.

I would check that "lst" is actually a list when you are assuming that it is (maybe some bug before calling this method resulted in "lst" becoming an integer).

I think the first condition of your last if statement is protecting the len() function there, but it never hurts to check it out if I'm wront about "lst" just being an integer sometimes.

Here is a possible solution.

def recListSum(lst):
    '''Takes an arbitrarily nested list as a parameter and returns the sum of
the numbers in the list'''
    # handle trivial cases
    if len(lst) == 0:
        return 0
    if len(lst) == 1:
        return lst[0]

    # sum and unfold
    total = 0
    new_lst = []
    for item in lst:
        if isinstance(item, list):
            new_lst += item
        else:
            total += item
    new_lst.append(total)

    # recurse
    return recListSum(new_lst)

A simple way is listed below. I assume that lst are list which consist of list , int or float

def recListSum(lst):
    if type(lst) in (int,float):
        return lst
    elif not type(lst) is list:
        raise TypeError
    elif len(lst) == 0:
        return 0
    else:
        return recListSum(lst[0])+recListSum(lst[1:])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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