Find the most similar document

Search engines turn text into vectors and rank documents by the angle to the query vector.

What to build

Given a query vector and several document vectors, find the document with the highest cosine similarity to the query.

Requirements

  • Read the query, the number of documents n, and n document vectors.
  • Compute the cosine similarity of the query with each document.
  • Print the number of the best document (counting from 1) and its similarity with 4 decimal places.

Input

Line 1: the query, 2 to 6 whole numbers. Line 2: n (1 to 8). Then n lines, each a document with the same count of whole numbers. No vector is all zeros.

Output

Two lines: best N and similarity S, with S to 4 decimal places.

Constraints

The entries are between 0 and 20. The tests contain no ties.

Example

Input:

1 0 2
2
3 1 0
2 0 3

Output:

best 2
similarity 0.9923

Why it works

Cosine similarity compares directions and ignores length, so a short and a long document about the same topic both match well. The best match is the document whose vector points most nearly the same way as the query.

Examples

Example 1 · Input
1 0 2
2
3 1 0
2 0 3
Expected output
best 2
similarity 0.9923
Example 2 · Input
1 1
3
1 0
0 1
5 4
Expected output
best 3
similarity 0.9939

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Cosine similarity is dot ÷ (|q| × |d|).

Hint 2

Compute it for each document, remember the largest, and keep the first one if there is a tie.

Hint 3

Numbers are counted from 1. Print the similarity with `:.4f`.

Solution

Show one correct solution (try it yourself first)
from math import sqrt

query = [int(x) for x in input().split()]
n = int(input())
docs = [[int(x) for x in input().split()] for _ in range(n)]

def norm(v):
    return sqrt(sum(a * a for a in v))

best, best_sim = 0, -2.0
for i, d in enumerate(docs):
    sim = sum(a * b for a, b in zip(query, d)) / (norm(query) * norm(d))
    if sim > best_sim:
        best, best_sim = i, sim
print("best", best + 1)
print(f"similarity {best_sim:.4f}")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Vectors and the dot product →