简体   繁体   中英

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])) 

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM