0

I'm a novice at Python and I'm trying to get to grips with concepts such as recursion.

I'm trying to create a recursive function that takes each element of a list and returns the product of those elements.

I have a non-recursive function that works:

elements = [1.1,2.2,3.3,12.12]

def mult1(elements):
    total = 1
    for i in elements:
        total = total * i
    return total

I want to be able to compute this function but recursively.

Currently my code for the recursive function is:

list = [1,2,3,10]

def mult2(list):
    i = len(list)
    total = 1
    if (i == 0):
        return total
    else:
        total = total * i
        mult2(i-1)

I don't get any errors (I'm using Komodo) but it doesn't return a value. If anyone could explain to me what the issue is that would be great.

Thanks!

3
  • 2
    Basically you need to return the value mult2(i-1) with return mult2(i-1) Commented Nov 26, 2015 at 13:19
  • Also, you initially call mult2 with a list as the parameter, but in the last line you call it with a number as the parameter Commented Nov 26, 2015 at 13:23
  • I've changed my code. I'll type it in here. list = [1,2,3,4,10] def mult2(list): if not list: return 0 mult2(list[0] * list[1:]). Got any ideas? Commented Nov 26, 2015 at 16:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.