Home > other >  How to calculate dot product recursively?
How to calculate dot product recursively?

Time:09-19

I need to write a function that calculates the dot product recursively, I made it so you can calculate up to 4 dimensions, but when I try to make it recursive I get an error because of infinite recursion. I've tried setting recursion limits, but no matter the limit, it always says the limit is too low. How should I go about this?

#Dot product not recursively
def dot(L, K):
""" Calculates dot product of lists L and K
    Empty lists or lists of unequal length return 0
    L, K are floats or ints
"""

x = len(L) - 1

if len(L) != len(K):
    return 0
if len(L) == 0:
    return 0
if len(K) == 0:
    return 0
elif len(L) & len(K) == 1:
    return L[x]*K[x]
elif len(L) & len(K) == 2:
    return L[x] * K[x]   L[x-1] * K[x-1]
elif len(L) & len(K) == 3:
    return L[x] * K[x]   L[x-1] * K[x-1]   L[x-2] * K[x-2]
elif len(L) & len(K) == 4:
    return L[x] * K[x]   L[x-1] * K[x-1]   L[x-2] * K[x-2]   L[x-3] * K[x-3]

#Tries (kind of, I deleted most of my code...)
#    elif len(L) == len(K):                          #Infinite Recursion Error
#       return L[x] * K[x]   (dot(L, K)-1)
#    elif len(L) == len(K):                          #Object of Type int has no len() Error
#       return L[x] * K[x]   dot(L[x-1], K[x-1])

CodePudding user response:

Your last expression dot(L[x-1], K[x-1]) is close, but when you write L[x-1] — it's a number, but it should be a list. You can pass a slices (other lists) with all elements except the last: dot(L[0:x], K[0:x]).

  • Related