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?
CodePudding user response:
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
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.
CodePudding user response:
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