1

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

5
  • 1
    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 Commented Oct 28, 2021 at 20:50
  • BTW, you can combine the two functions by giving i a default value. Commented Oct 28, 2021 at 20:53
  • 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. Commented Oct 28, 2021 at 20:53
  • 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 Commented Oct 28, 2021 at 20:54
  • Because multAllRec() unconditionally calls itself. This needs to be be done conditionally in order for it to stop doing so. Commented Oct 28, 2021 at 21:04

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.