1
votes

I am tyring to multiply the values in an array recursively but I get an error after running the following code :

def multAll(k,A) : 
    multAllRec(k,A,0)
def multAllRec(k,A,i) : 
    if i<len(A):
        A[i] *= k
    multAllRec(k, A, i + 1)

multAll(10,[5,12,31,7,25])

Error : RecursionError: maximum recursion depth exceeded while calling a Python object

2
You need to add a base case to return at some point. Every call of multAllRec is guaranteed to call itself again so you will always hit the limit. Looks like you want something along the lines of if i >= len(A): return - Locke
BTW, you can combine the two functions by giving i a default value. - Barmar
You are in front of a stack overflow (like the forum's name). As Locke said, you are recursively calling the function multAllRec without return, that is what is causing the error. - Alexandro Palacios
thanks, I modified the function so that it contains def multAll(k,A): return multAllRec(k,A,0) def multAllRec(k,A,i): if i >= len(A): return A - Dran Kisnosx
Because multAllRec() unconditionally calls itself. This needs to be be done conditionally in order for it to stop doing so. - martineau

2 Answers

1
votes

You should do something to return a value. Within at list a Conditional statement to prevent the infinite loop recursive calls.

def multAll(k,A) :
    multAllRec(k,A,0)
    return A

def multAllRec(k,A,i) :
    if i<len(A):
        A[i] *= k
        multAllRec(k, A, i + 1)
    else:
        return A    
    

B=multAll(10,[5,12,31,7,25])

print(B)

[Output]

[50, 120, 310, 70, 250]
0
votes

You can use something like this:

def mult_all_rec(k, A, i=0):
    if i < len(A):
        A[i] *= k
        mult_all_rec(k, A, i + 1)
    return


some_list = [5, 12, 31, 7, 25]
mult_all_rec(10, some_list)

print(some_list)

Here, there's no need for a multAll method, this recursion can be done by assigning a default value to i, 0. (as indef mult_all_rec(k, A, i=0):)

when if not i < len(A), you need to return. This is called base condition.

Every recursion must have a base condition.