Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 411
Chris Avatar asked Nov 21 '25 08:11

Chris


2 Answers

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
like image 114
Bhargav Rao Avatar answered Nov 23 '25 22:11

Bhargav Rao


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)
like image 30
Łukasz Rogalski Avatar answered Nov 23 '25 21:11

Łukasz Rogalski