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

def multAllRec(k,A,i):
    if i == A[len(A)-1]:
        return

    if i < len(A):
        A[i] = A[i]*k
        return A[i]

    return multAllRec(k, A, i+1)

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

I'm using python to create a recursive function that multiplies the elements in the array by the variable k. Here in this code I am doing the recursive function but it is only returning 50 when it should be returning [50,120,310,70,250]. It is only multiplying the first element of the array.

What am I doing wrong?

0

3 Answers 3

1

The function should return a list with only the first item of the list multiplied, while passing on the rest of the items to the recursive call:

def multAll(k, A):
    return A and [k * A[0], *multAll(k, A[1:])]

so that:

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

returns:

[50, 120, 310, 70, 250]
Sign up to request clarification or add additional context in comments.

Comments

1

In your code you have to change 2 lines, return A on complete, and don't return A[i] when updating value

Edit: compare length using just len(A)

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

def multAllRec(k,A,i):
    if i == len(A):
        return A

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

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

Comments

0

Why use recursion here? Seems like more work than is needed. Just use a for loop or comprehension.

def multAll(k, A):
    return [k*n for n in A]    

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

1 Comment

Using recursion is likely the main requirement of the OP's homework.

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.