praneeth bharadwaj
praneeth bharadwaj

Reputation: 1

how to find dot product of two lists using only recursion(no loops or list comprehensions) in python?

  1. Need to find dot product of two lists
  2. Cannot use for, while etc loops
  3. cannot use list comprehensions

  4. solution has to be purely in recursion terms

    def mult(n, m): 
        if n == 0: 
            return 0 
        elif n == 1: 
            return m 
        elif n < 0: 
            return -mult(-n, m) 
        else: return m + mult(n-1, m) 
    
    def dot(l1,l2): 
        if len(l1)==len(l2) and len(l2)!=0: 
            return sum([mult(l1[n],l2[n]) for n in range(len(l2))]) 
        else: return 0 
    
    print(dot([1,2],[3,4]))
    

Upvotes: -1

Views: 2454

Answers (2)

Michael Geinopolos
Michael Geinopolos

Reputation: 1

def dotproduct(x,y):
    'returns the dot product of two vectors'
    if len(x) and len(y) == 1:
        return x[0]*y[0]
    else:
        n = x[0]
        m = y[0]
        x.remove(n)
        y.remove(m)
        return dotproduct(x,y) + n*m

Upvotes: -1

xnx
xnx

Reputation: 25538

If the vectors are lists, the dot product is

v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2] + ...

So if a single recursion step can multiply the first pair of numbers and then add it to the same function called on the remainder of the lists until the lists are empty. We treat the process as:

(v1[0]*v2[0] + (v1[1]*v2[1] + (v1[2]*v2[2] + ... + 0) ... )))

For example,

def dot(v1, v2):
    if not v1:
        # We're done: nothing to add on
        return 0
    # Multiply the first numbers and add to the dot product of the rest
    return v1[0] * v2[0] + dot(v1[1:],v2[1:])

dp = dot([1,2,3],[4,1,8])
print(dp)

30  # =(1*4 + (2*1 + (3*8)))

Upvotes: 1

Related Questions