Home > Software design >  How do I multiply 2 lists in Python using recursion?
How do I multiply 2 lists in Python using recursion?

Time:10-01

So for school I have this exercise where I have to multiply 2 lists using recursion. If both string are not equally long and if there is nothing in the list it has to return 0. This is what I have:

def dot(L, K):
    if len(L) != len(K):
        return 0
    elif len(L) or len(K) == 0:
        return 0
    else:

The output has to be something like this:

In [1]: dot([5, 3], [6, 4])
Out[1]: 42.0

So 5 * 6 = 30 and 3 * 4 = 12 = 42 total.

Can someone help me out please?

CodePudding user response:

Try:

def dot(k, l, total = 0):
    assert len(k) == len(l), "lists are not the same size"
    if k and l:
        total  = k[0] * l[0] 
        return dot(k[1:], l[1:], total)
    else:
        return total

print(dot([5, 3], [6, 4])) # output: 42

CodePudding user response:

Here is a verbose answer, hopefully this helps you understand the logic of recursion.

def helper(x, y, idx, n, curr):
    i = x[idx]
    j = y[idx]
    tmp = i * j
    res = curr   tmp
    if idx == n - 1:  # checks to see if we are at the end of the array
        return res
    else:
        return helper(x, y, idx   1, n, res)


def dot(k, l):
    if len(k) != len(l):
        return 0
    elif not len(k):
        return 0
    else:
        return helper(k, l, 0, len(k), 0)

We slide down the arrays in tandem, keeping track of the index. We check on every iteration if we have reached the end of the array which would be the len(array) - 1. If we reach the end we return the result, otherwise we continue down the array incrementing the current index by 1.

  • Related