TorchedUp
LearnBetaProblemsSystem DesignSoonPremium
TorchedUp
LearnBetaProblemsSystem DesignSoonPremium
←

161. Cosine Top-K Retrieval

Easy

Given a query embedding and a matrix of document embeddings, return the indices of the top-k documents by cosine similarity.

Signature: def topk_cosine(query: np.ndarray, docs: np.ndarray, k: int) -> list

  • query shape (d,), docs shape (n, d)
  • Cosine sim: (docs @ query) / (||query|| * ||docs_i||)
  • Return a Python list of indices, most-similar first.

Constraint: Use np.argsort (descending).

Math

cos(q,di​)=∥q∥∥di​∥q⋅di​​

Asked at

NumPy

import numpy as np

 

def topk_cosine(...):

    pass

🔒

Premium problem

Free accounts include problems #1–20. Upgrade to unlock the editor, hidden test cases, and reference solutions for every problem.

Upgrade to PremiumBack to problems

Already premium?