Please login

Prime #### Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime #### Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

# Finding minimum scalar product of two vectors in Python

## Minimum scalar product of two vectors

In this program we will be Finding minimum scalar product of two vectors in Python . The input is two arrays ( vectors are represented as arrays ) and the output is minimum scalar product. The scalar product is nothing but dot product of two arrays. Dot product is the sum of the products of the corresponding entries of the two sequences of numbers.

• Example : Vector 1 – 2 3 1 4, Vector 2- 3 7 1 9
• Sort Vector 1 in ascending order 1 2 3 4
• Sort Vector 2 in descending order 9 7 3 1
• Multiply the same index elements in both vectors -1*9+2*7+3*3+4*1=36
• Minimum scalar product of two vectors=36 ## Algorithm 1:

1. Input two arrays
2. Initialize a variable “s” to store sum
3. Sort the first array in ascending order (use sort() in python )
4. Sort the second array in descending order
5. Now multiply the elements at same index in both arrays and then find sum of products
6. The sum of products is nothing but minimum scalar product
7. Display minimum scalar product of two vectors . Finding minimum scalar product of two vectors in Python

## Python Code 1:

#Syntax for reading space seperated integers
l1=list(map(int,input(“Enter array1”).split()))
l2=list(map(int,input(“Enter array2”).split()))
#Sort in ascending order
l1.sort()
#Sort in descending order
l2.sort(reverse=True)
s=0
for i in range(0,len(l1)):
for j in range(0,len(l2)):
if(i==j):
s+=l1[i]*l2[j]
print(“Minimum scalar product of two arrays is”,end=” “)
print(s)

## Output:

Enter array1 1 2 3 4
Enter array2 1 1 2 5
Minimum scalar product of two arrays is 16

## Algorithm 2:

As in previous code we used to loops (inner and outer loops) which will increase time complexity. So we are reducing Time complexity of the previous code now by using one loop and removing inner loop.

## Python code 2:

l1=list(map(int,input(“Enter array1”).split()))
l2=list(map(int,input(“Enter array2”).split()))
#Sort in ascending order
l1.sort()
#Sort in descending order
l2.sort(reverse=True)
s=0
for i in range(0,len(l1)):
s+=l1[i]*l2[i]
print(“Minimum scalar product of two arrays is”,end=” “)
print(s)

### Output:

`Enter array1 1 2 3 4Enter array2 1 1 2 5Minimum scalar product of two arrays is 16`