Possible Duplicate:
calling func. change the input
I have to write a recursive function that takes a list of numbers in input and returns a list of numbers in output, for example called like this:
rec_cumsum([2,2,2,3])
the output should be like:
[2,4,6,9]
Thing is, I cant seem to get my head around for this to work.. this got me questioning my whole recursive thinking..
what i have so far is :
newlist = []
k = 1
def rec_cumsum(numbers):
if len(numbers) == 0:
return 0
if len(numbers) > 1 and len(numbers) != (k+1):
newlist[k+1] == newlist[k+1] + newlist[k]
k = k+1
return rec_cumsum(numbers)
but I’m getting errors which doesn’t really make any sense to me.
the recursion should always take the number, and add it to the one before it, than save it in the next location of the list.. (new one or original one)
I would write it like this:
Now to look at your code (note I didn’t actually work through the logic to decide whether it would give the correct result, the following only addresses possible exceptions that your code is probably throwing):
You’re probably getting an IndexError because of this line:
You’re assigning to a list position which doesn’t exist yet. You could pre-allocate your list:
but even if you fix that, you’ll get a recursion error with your code because of the line:
The problem here is that on the left hand side,
kis local whereas on the right hand side,kis global. So essentially each time you run this, you’re getting the localk == 2and not touching the global one. If you really want to modify the globalk, you need to declarekas global viaglobal k. Of course, then you need to resetkevery time you’re going to use this function which would be a somewhat strange API.