The basic operation behind semantic search: compare two embedding vectors.
What to build
A program that prints the dot product and the cosine similarity of two vectors.
Requirements
- Print
dot Dandcosine C, each with 4 decimal places.
Input
Two lines, each a vector with the same number of numbers.
Output
Two lines.
Constraints
1 to 1000 numbers per vector; neither vector is all zeros.
Example
Input:
1 0
0 1
Output:
dot 0.0000
cosine 0.0000
Why it works
The dot product grows when the vectors point the same way, and dividing by the lengths removes the effect of their sizes, leaving only the angle between them.
Examples
Example 1 · Input
1 0 0 1
Expected output
dot 0.0000 cosine 0.0000
Example 2 · Input
1 2 3 2 4 6
Expected output
dot 28.0000 cosine 1.0000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Multiply matching numbers and add them up for the dot product.
Hint 2
Cosine similarity is the dot product divided by the product of the two lengths (square roots of each vector's sum of squares).
Solution
Show one correct solution (try it yourself first)
import math
a = list(map(float, input().split()))
b = list(map(float, input().split()))
dot = sum(x * y for x, y in zip(a, b))
cos = dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))
print(f"dot {dot:.4f}")
print(f"cosine {cos:.4f}")