Simple recursive sum function | what's the cause of the weird behaviour?
Rotwang
sg552 at hotmail.co.uk
Sat Jul 6 16:25:51 EDT 2013
On 06/07/2013 21:10, Rotwang wrote:
> [...]
>
> It's not quite clear to me what the OP's intentions are in the general
> case, but calling supersum(item, start) seems odd - for example, is the
> following desirable?
>
> >>> supersum([[1], [2], [3]], 4)
> 22
>
> I would have thought that the "correct" answer would be 10. How about
> the following?
>
> def supersum(sequence, start = 0):
> result = start
> for item in reversed(sequence):
> try:
> result = supersum(item, result)
> except:
> result = item + result
> return result
Sorry, I've no idea what I was thinking with that reversed thing. The
following seems better:
def supersum(sequence, start = 0):
result = start
for item in sequence:
try:
result = supersum(item, result)
except:
result = result + item
return result
More information about the Python-list
mailing list