Reputation: 815
I'm trying to create a function that multiplies each item in a list and returns the total. The function doesn't stop running until memory runs out. Can someone please explain to me why this isn't working?
items = [1,2,3,4,10]
def mult2(items):
if not items:
return 0
return mult2(items[0]) * mult2(items[1:])
mult2(items)
Upvotes: 3
Views: 4623
Reputation: 6185
Fixed the errors in the OP, and this works:
items = [1,2,3,4,10]
def mult2(items):
if len(items) == 1:
return items[0]
return items[0] * mult2(items[1:])
print "sum:",mult2(items)
Upvotes: 1
Reputation: 23233
There are two issues:
Single element is passed to mult2
, but sequence is expected. That's why TypeError: 'int' object has no attribute '__getitem__'
is raised, due to trying to subscripting int (code being executed resolves to 1[1:]
which is simply not possible).
Your exit condition is broken. Neutral multiplier is 1, not 0.
After fixes your code would look like this:
def mult2(seq):
if not seq:
return 1
return seq[0] * mult2(seq[1:])
items = [1,2,3,4,10]
assert 240 == mult2(items)
Upvotes: 2
Reputation: 15934
You don't have a base case for your recursion that works properly.
Consider calling mult2
with [1,2,3]
this gets to the return statement which called mult2
with 1
and with [1,2]
.
The problem is in the call to mult2
with the parameter 1
which is just an integer. When you get to the recursive part there's no indexing available because items
is just an int at this point, so items[0]
and items[1:]
don't make sense at this point.
Upvotes: 1
Reputation: 52141
Couple of mistakes here
Corrected code
def mult2(items):
if len(items)==1:
return items[0]
return mult2([items[0]]) * mult2(items[1:])
Demo
>>> items = [1,2,3,4,10]
>>>
>>> def mult2(items):
... if len(items)==1:
... return items[0]
... return mult2([items[0]]) * mult2(items[1:])
...
>>> print(mult2(items))
240
Upvotes: 3