user3050527
user3050527

Reputation: 931

what's wrong with my code? recursively finding sum of nested list

I'm trying to make a function that returns the sum of all integers in a tree list in the format:

element 1 is an integer
element 2 is another treelist or None
element 3 is another treelist or None

ex: [1,[1,None,None],None]

so basically i want my function to add up all the integers in that list and return 2.

This is what i made so far..

def sum_nested(t):
    sum = 0
    for i in t:
        if type(i) == type(None):
           sum += 0
        if type(i) == list:
           return sum_nested(i)
        else:
            sum = sum + i

    return sum  

However, I get the error:

builtins.TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

cant seem to figure out what to do when i hit that None type..any suggestions?

Upvotes: 0

Views: 131

Answers (3)

Joel Cornett
Joel Cornett

Reputation: 24788

How about:

def sum_nested(seq):

    # Don't use `sum` as a variable name, as it shadows the builtin `sum()`
    total = 0
    for item in seq:

        # This will allow you to sum *any* iterable (tuples, for example)
        if hasattr(item, '__iter__'): 

            # Use the `+=` syntactic sugar
            total += sum_nested(item) 
        else:

            # `None or 0` evaluates to 0 :)
            total += item or 0 

    return total

Upvotes: 2

m.wasowski
m.wasowski

Reputation: 6387

def sum_nested(seq):
    total = 0
    for item in seq:
        if hasattr(item, '__iter__'): 
            total += sum_nested(item)
            continue
        try:
            total += item
        except TypeError:
            continue
    return total

print sum_nested([2, ['text', [None, 1], [int, [True, None], 5]]])
# True counts as 1

Upvotes: 1

BoshWash
BoshWash

Reputation: 5440

Try this:

t = [1, [1, None, None], None]
def sum_nested(t):
    sum = 0
    for i in t:
        if type(i) is int:
            sum += 1
        elif type(i) == list:
           sum += sum_nested(i)

    return sum

print(sum_nested(t))

if you want to test if something is None the shortest form is:

if i:

But in your case that's not really necessary since you're not changing sum anyways

Upvotes: 1

Related Questions