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

Joshua Landau joshua.landau.ws at gmail.com
Sat Jul 6 20:43:42 CEST 2013


On 6 July 2013 13:59, Russel Walker <russ.pobox at gmail.com> wrote:
> Since I've already wasted a thread I might as well...
>
> Does this serve as an acceptable solution?
>
> def supersum(sequence, start=0):
>     result = type(start)()
>     for item in sequence:
>         try:
>             result += supersum(item, start)
>         except:
>             result += item
>     return result

It's probably more robust to do:

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

as that way you aren't assuming the signature of type(start).



More information about the Python-list mailing list