Advertisement
smj007

Dot product of sparse vectors

Aug 15th, 2024
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  1. class SparseVector:
  2.     def __init__(self, nums: List[int]):
  3.         self.hashmap = {}
  4.         for ind, num in enumerate(nums):
  5.             self.hashmap[ind] = num
  6.  
  7.     # Return the dotProduct of two sparse vectors
  8.     def dotProduct(self, vec: 'SparseVector') -> int:
  9.         keys1 = list(self.hashmap.keys())
  10.         keys2 = list(vec.hashmap.keys())
  11.         values1 = list(self.hashmap.values())
  12.         values2 = list(vec.hashmap.values())
  13.  
  14.         result = 0
  15.         i, j = 0, 0
  16.  
  17.         while(i < len(keys1) and j < len(keys2)):
  18.             if keys1[i] < keys2[j]:
  19.                 i += 1
  20.             elif keys1[i] > keys2[j]:
  21.                 j += 1
  22.             else:
  23.                 result += values1[i] * values2[j]
  24.                 i += 1
  25.                 j += 1
  26.  
  27.         return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement