dot_product_of_two_sparse_vectors

 1# @leet start
 2class SparseVector:
 3    """
 4    This question asks us to compute the dot product of two matrices that are
 5    sparse. We don't want to multiply a bunch of zeroes, so we can keep the non
 6    zero numbers in a hashmap and then sum the result later on.
 7    """
 8
 9    def __init__(self, nums: list[int]):
10        self.nonzeroes = {}
11        for i, n in enumerate(nums):
12            if n != 0:
13                self.nonzeroes[i] = n
14
15    # Return the dotProduct of two sparse vectors
16    def dotProduct(self, vec: "SparseVector") -> int:
17        result = 0
18        for i, n in self.nonzeroes.items():
19            if i in vec.nonzeroes:
20                result += n * vec.nonzeroes[i]
21        return result
22
23
24# Your SparseVector object will be instantiated and called as such:
25# v1 = SparseVector(nums1)
26# v2 = SparseVector(nums2)
27# ans = v1.dotProduct(v2)
28# @leet end
29
30
31def test():
32    assert 2 + 2 == 4
class SparseVector:
 3class SparseVector:
 4    """
 5    This question asks us to compute the dot product of two matrices that are
 6    sparse. We don't want to multiply a bunch of zeroes, so we can keep the non
 7    zero numbers in a hashmap and then sum the result later on.
 8    """
 9
10    def __init__(self, nums: list[int]):
11        self.nonzeroes = {}
12        for i, n in enumerate(nums):
13            if n != 0:
14                self.nonzeroes[i] = n
15
16    # Return the dotProduct of two sparse vectors
17    def dotProduct(self, vec: "SparseVector") -> int:
18        result = 0
19        for i, n in self.nonzeroes.items():
20            if i in vec.nonzeroes:
21                result += n * vec.nonzeroes[i]
22        return result

This question asks us to compute the dot product of two matrices that are sparse. We don't want to multiply a bunch of zeroes, so we can keep the non zero numbers in a hashmap and then sum the result later on.

SparseVector(nums: list[int])
10    def __init__(self, nums: list[int]):
11        self.nonzeroes = {}
12        for i, n in enumerate(nums):
13            if n != 0:
14                self.nonzeroes[i] = n
nonzeroes
def dotProduct(self, vec: SparseVector) -> int:
17    def dotProduct(self, vec: "SparseVector") -> int:
18        result = 0
19        for i, n in self.nonzeroes.items():
20            if i in vec.nonzeroes:
21                result += n * vec.nonzeroes[i]
22        return result
def test():
32def test():
33    assert 2 + 2 == 4