- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
otherwise when nums[i] of vector1 is same as 0, then
go for next iteration
res := res + v * nums[i] of vector1
Let us see the following implementation to get better understanding −
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))
[1, 0, 0, 0, 1], [0, 0, 0, 1, 1]
- Return the dot product of two vectors in Python
- Return the dot product of two multidimensional vectors in Python
- C++ Program for dot product and cross product of two vectors
- Program to find dot product of run length encoded vectors in Python
- Return the dot product of One-Dimensional vectors in Python
- How to find the dot product of two matrices in R?
- How to find the dot product of two pandas series objects?
- C++ Program to Compute Cross Product of Two Vectors
- Program to find out the k-th largest product of elements of two arrays in Python
- Return the cross product of two (arrays of) vectors in Python
- Python program to find Cartesian product of two lists
- Return the dot product of two masked arrays in Numpy
- How to find the cross product of two vectors in R by adding the elements?
- Return the multiple vector cross product of two (arrays of) vectors in Python
- Python Program to Find the Product of two Numbers Using Recursion