recursion gotcha?

cnb circularfunc at yahoo.se
Sun Sep 14 04:01:42 EDT 2008


this recursive definition of sum thrumped me, is this some sort of
gotcha or am I just braindead today?
and yes i know this is easy a a for x in xs acc += x or just using the
builtin.

def suma(xs, acc=0):
	if len(xs) == 0:
		acc
	else:
		suma(xs[1:], acc+xs[0])

it returns none.



def summa(xs):
	if not xs:
		0
	else:
		xs[0]+summa(xs[1:])


Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    summa([1,2,3,4,5])
  File "<pyshell#5>", line 5, in summa
    xs[0]+summa(xs[1:])
  File "<pyshell#5>", line 5, in summa
    xs[0]+summa(xs[1:])
  File "<pyshell#5>", line 5, in summa
    xs[0]+summa(xs[1:])
  File "<pyshell#5>", line 5, in summa
    xs[0]+summa(xs[1:])
  File "<pyshell#5>", line 5, in summa
    xs[0]+summa(xs[1:])
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'



More information about the Python-list mailing list