Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Cosine Similarity From Scratch

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

Your question is Cosine Similarity From Scratch. 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

Cognizant Neuro AI may compare embedding vectors to identify semantically similar text. Implement cosine similarity from scratch using only Python's built-in operations.

Given two non-empty vectors a and b of equal length, return their cosine similarity:

similarity = (a · b) / (||a|| × ||b||)

The dot product is the sum of pairwise products, and each norm is the square root of the sum of squared components. If either vector is a zero vector, return 0.0 because its direction is undefined.

Formal Specification

  • Input: Two lists of integers or floating-point numbers, a and b, with equal non-zero lengths.
  • Output: A floating-point number in the range [-1.0, 1.0], subject to normal floating-point precision.
  • Do not use NumPy, scikit-learn, or other vector libraries.

Constraints

  • 1 <= len(a) = len(b) <= 10^5
  • -10^6 <= a[i], b[i] <= 10^6
  • Both vectors are non-empty and have equal lengths
  • Inputs contain finite integers or floating-point values

Function Signature

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