- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
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 −
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
- Related Articles
- Return the dot product of two vectors in Python
- Program to find dot product of run length encoded vectors in Python
- Return the dot product of two multidimensional vectors in Python
- C++ Program for dot product and cross product of two vectors
- Return the dot product of One-Dimensional vectors in Python
- C++ Program to Compute Cross Product of Two Vectors
- How to find the dot product of two matrices in R?
- 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
- How to find the dot product of two pandas series objects?
- Program to find out the scalar products of vectors generated from an infinite sequence in Python
- Return the multiple vector cross product of two (arrays of) vectors in Python
- How to find the cross product of two vectors in R by adding the elements?
- Python program to find Cartesian product of two lists
- Return the cross product of two (arrays of) vectors with different dimensions in Python

Advertisements