Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Start free
Cosine Similarity
00:00
5 left

Cosine Similarity

EasyPython

Problem

A search and discovery system 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):
Interviewer

Whenever you're ready, walk me through your approach or go straight to the code. The requirements are in the Question tab.

Sign up free to run or submit. Log in
Code
Sign up free to run your code. Your draft is saved.Run with a free accountLog inLn 2
Run your code to see test output here.