Dran Kisnosx
Dran Kisnosx

Reputation: 11

Why am I getting this error for maximum recursive calls?

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

Upvotes: 1

Views: 125

Answers (2)

Burakhan Aksoy
Burakhan Aksoy

Reputation: 323

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.

Upvotes: 0

AziMez
AziMez

Reputation: 2072

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]

Upvotes: 1

Related Questions