Hassan
Hassan

Reputation: 49

Trying to return values using recursion but values are not showing

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?

Upvotes: 0

Views: 78

Answers (3)

Jacek Rojek
Jacek Rojek

Reputation: 1122

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])

Upvotes: 1

Jab
Jab

Reputation: 27485

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]))

Upvotes: 0

blhsing
blhsing

Reputation: 106455

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]

Upvotes: 1

Related Questions