Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Cosine Similarity in Python

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Cosine Similarity in Python. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Ancestry search and discovery features can rank documents by how closely their embeddings match a user's interests. Given one user embedding and a matrix of document embeddings, compute the cosine similarity between the user vector and every document vector.

Return one similarity score per document, preserving the input order. If either the user embedding or a document embedding has zero magnitude, define its similarity as 0.0 to avoid division by zero.

Formal Specification

Implement cosine_similarities(user_embedding, document_embeddings). The user embedding is a list of d real numbers, and document_embeddings is a list of n vectors, each containing exactly d real numbers. Return a list of n floating-point values, where each value is:

dot(user, document) / (||user|| * ||document||)

The implementation should compute the user's norm once rather than recomputing it for every document.

Constraints

  • 1 <= len(user_embedding) <= 10^4
  • 0 <= len(document_embeddings) <= 10^4
  • Every document embedding has the same dimension as user_embedding
  • The total number of embedding values is at most 10^7
  • Values are finite real numbers

Function Signature

def cosine_similarities(user_embedding, document_embeddings):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output