# Program to find dot product of run length encoded vectors in Python

PythonServer Side ProgrammingProgramming

Suppose we have two lists nums1 and nums2. Each of these two list are representing a vector in run-length encoded form. So as an example, a vector [1, 1, 1, 2, 2, 2, 2] is represented as [3, 1, 4, 2]. (because there are 3 ones and 4 twos). So we have to find the dot product of these two vectors. (The dot product is the sum of element wise multiplication of items present in two vectors).

So, if the input is like nums1 = [2, 7, 5, 3] nums2 = [3, 5, 4, 2], then the output will be 109 because, the vectors are like [7, 7, 3, 3, 3, 3, 3] • [5, 5, 5, 2, 2, 2, 2] = 7*5 + 7*5 + 3*5 + 3*2 + 3*2 + 3*2 + 3*2 = 35 + 35 + 15 + 6 + 6 + 6 + 6 = 109.

To solve this, we will follow these steps −

• ans := 0
• while nums1 and nums2 both are non-empty, do
• val1 := last element from nums1 and delete the last item
• count1 := last element from nums1 and delete the last item
• val2 := last element from nums2 and delete the last item
• count2 := last element from nums2 and delete the last item
• ans := ans + (val1 * val2) * (minimum of count2 and count1)
• if count2 > count1, then
• insert |count2 - count1| at the end of nums2
• insert val2 at the end of nums2
• otherwise when count1 > count2, then
• insert |count2 - count1| at the end of nums1
• insert val1 at the end of nums1
• return ans

## Example

Let us see the following implementation to get better understanding −

def solve(nums1, nums2):
ans = 0

while nums1 and nums2:
val1 = nums1.pop()
count1 = nums1.pop()
val2 = nums2.pop()
count2 = nums2.pop()

ans += (val1 * val2) * min(count2, count1)

if count2 > count1:
nums2.append(abs(count2 - count1))
nums2.append(val2)
elif count1 > count2:
nums1.append(abs(count2 - count1))
nums1.append(val1)

return ans

nums1 = [2, 7, 5, 3]
nums2 = [3, 5, 4, 2]
print(solve(nums1, nums2))

## Input

[2, 7, 5, 3], [3, 5, 4, 2]

## Output

109
Published on 16-Oct-2021 10:47:19