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

Chris Angelico rosuav at gmail.com
Sat Jul 6 13:22:40 EDT 2013


On Sat, Jul 6, 2013 at 10:37 PM, Russel Walker <russ.pobox at gmail.com> wrote:
> 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]
>>>>

You have a problem of specification here. What should supersum do with
the list [1]? Should it recurse into it, or append it as a list? It
can't do both. For a list flattener, you would need to either use
.append for each element you come across, or .extend with each list,
with some kind of check to find whether you should recurse or not.

Still, it's a fun thing to play with. I like code golfing these sorts
of trinketty functions, just for fun :)

ChrisA



More information about the Python-list mailing list