Simple recursive sum function | what's the cause of the weird behaviour?

Russel Walker russ.pobox at gmail.com
Sat Jul 6 14:37:38 CEST 2013


I know this is simple but I've been starring at it for half an hour and trying all sorts of things in the interpreter but I just can't see where it's wrong.

def supersum(sequence, start=0):
    result = start
    for item in sequence:
        try:
            result += supersum(item, start)
        except:
            result += item
    return result

It's supposed to work like the builtin sum, but on multidimensional lists and also with the optional start parameter accepting something like an empty list and so would also works as a robust list flattener. It's just for kicks, I'm not actually going to use it for anything.


This works:
- - - - - -
>>> x = [[1], [2], [3]]
>>> supersum(x)
6
>>> supersum(x, [])
[1, 2, 3]
>>> 


This does not:
- - - - - - - 
>>> x = [[[1], [2]], [3]]
>>> supersum(x, [])
[1, 2, 1, 2, 3]
>>> 




More information about the Python-list mailing list