recursion gotcha?
rs387
rstarkov at gmail.com
Sun Sep 14 04:06:41 EDT 2008
On Sep 14, 9:01 am, cnb <circularf... at yahoo.se> wrote:
> def suma(xs, acc=0):
> if len(xs) == 0:
> acc
> else:
> suma(xs[1:], acc+xs[0])
>
> it returns none.
Yep, that's because there is no "return" statement anywhere. Python
doesn't return expressions "by default", like functional languages do,
so where you say "suma(xs[1:], acc+xs[0])" this just calls itself and
returns nothing.
Try this:
def suma(xs, acc=0):
if len(xs) == 0:
return acc
else:
return suma(xs[1:], acc+xs[0])
print suma([1, 2, 3, 4, 5])
(prints 15)
Roman
More information about the Python-list
mailing list