Program to find out the dot product of two sparse vectors in Python


Suppose, we have two sparse vectors represented in two lists. We have to return the dot product of the two sparse vectors. The vectors are represented as objects, and the lists are stored in a member variable 'nums' in the objects.

So, if the input is like vector1 = [1, 0, 0, 0, 1], vector2 = [0, 0, 0, 1, 1], then the output will be 1 The dot product is 1 * 0 + 0 * 0 + 0 * 0 + 0 * 1 + 1 * 1 = 1.

To solve this, we will follow these steps −

  • res := 0

  • for each index i, value v in nums of vector2, do

    • if v is same as 0, then

      • continue

    • otherwise when nums[i] of vector1 is same as 0, then

      • go for next iteration

    • otherwise,

      • res := res + v * nums[i] of vector1

  • return res

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
   def __init__(self, nums):
      self.nums = nums

   def solve(self, vec):
      res = 0
   for i, v in enumerate(vec.nums):
      if v == 0:
         continue
      elif self.nums[i] == 0:
         continue
      else:
         res += v * self.nums[i]
   return res

ob1, ob2 = Solution([1, 0, 0, 0, 1]), Solution([0, 0, 0, 1, 1])
print(ob1.solve(ob2))

Input

[1, 0, 0, 0, 1], [0, 0, 0, 1, 1]

Output

1

Updated on: 18-May-2021

490 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements