Chris
Chris

Reputation: 815

Recursive function of the product of a list not working

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

Answers (4)

boardrider
boardrider

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

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23233

There are two issues:

  1. 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).

  2. 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

shuttle87
shuttle87

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

Bhargav Rao
Bhargav Rao

Reputation: 52141

Couple of mistakes here

  1. Your base case is wrong. The Base case has to be when the list is reduced to a single element and you need to return 1 and not 0.
  2. You need to send a list with a single element and not the single element alone to meet your base case.

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

Related Questions