R
Russel Walker
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 emptylist 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:
- - - - - -
This does not:
- - - - - - -
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 emptylist 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]