user17051255
user17051255

Reputation:

How do I calculate dot product of 2 lists using recursion?

So for school I have this exercise where I have to calculate the dot product of 2 lists using recursion. If both string are not equally long or if there is nothing in the list it has to return 0. This is what I have so far:

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?

Upvotes: 1

Views: 541

Answers (4)

cdlane
cdlane

Reputation: 41885

Let's simplify this code by tossing those unnecessary else statements and get rid of the total argument while we're at it:

def dot(k, l):
    def dot_recursive(k, l):
        if k:  # k and l are same length
            return k[0] * l[0] + dot_recursive(k[1:], l[1:])

        return 0

    if (length := len(k)) == 0 or length != len(l):
        return 0

    return dot_recursive(k, l)

assert dot([5, 3], [6, 4]) == 42
assert dot([1, 0], [1]) == 0
assert dot([1], [1, 2]) == 0
assert dot([], []) == 0

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195508

Try:

def dot(L, K):
    if len(L) == 0 or len(L) != len(K):
        return 0
    else:
        return L[0] * K[0] + (0 if len(L) == 1 else dot(L[1:], K[1:]))


assert dot([5, 3], [6, 4]) == 42
assert dot([1, 0], [1]) == 0
assert dot([1], [1, 2]) == 0
assert dot([], []) == 0

Upvotes: 0

Gabio
Gabio

Reputation: 9504

Try:

def dot(k, l):
    if len(k) != len(l) or len(k) == 0:
        return 0
    else:
        return _dot(k, l, 0)

# recursive helper function that accumulates the total sum
def _dot(k, l, total):
    if k and l:
        total += k[0] * l[0] 
        return _dot(k[1:], l[1:], total)
    else:
        return total

# tests
assert dot([5, 3], [6, 4]) == 42
assert dot([1,0], [1]) == 0
assert dot([1], [1, 2]) == 0
assert dot([], []) == 0

Upvotes: 2

gold_cy
gold_cy

Reputation: 14226

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.

Upvotes: 1

Related Questions