Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
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
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess 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
Build my plan
Cosine Similarity in Python
00:00
5 left

Cosine Similarity in Python

EasyPython

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):
Interviewer

Your question is Cosine Similarity in Python. Start with the requirements in the Question tab.

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.
CodePython 3
Sign up free to run your codeLog inLn 2
Run your code to see test output here.