Hi, I am trying to calculate dot product of two sparse vector
This is my code, without fancy data structure
def dotproduct(nums1, nums2):
hm1= {} # hashmap for nums1
n = len(nums1)
if len(nums2) != n:
raise NameError('sizes of the two vectors must be equal')
for i in range(n):
if nums1[i]!=0:
hm1[i] = nums1[i]
res = 0
# for i in range(n):
# if nums2[i]!= 0 and i in hm1:
# res += nums2[i]*hm1[i]
for i in hm1:
if nums2[i]!= 0:
res += nums2[i]*hm1[i]
return res
and my code works well for a few test cases. I think it meet the algorithmic requirement – I store one of the vectors in a hashmap.
#nums1 = [1,0,0,2,3]
#nums2 = [0,3,0,4,0]
#nums1 = [0,1,0,0,0]
#nums2 = [0,0,0,0,2]
nums1 = [0,1,0,0,2,0,0]
nums2 = [1,0,0,0,3,0,4]
#nums1 = [0,1,0,0,2,0,0]
#nums2 = [1,0,0,0,3,0,4,2]
dotproduct(nums1, nums2)
Am I doing ok if I am asked this question at an interview?
Does the fancy data structure do me any good?
Thanks!