Distance Metrics

easy · vectors, distance, similarity

Distance Metrics

Implement common distance and similarity metrics used in machine learning.

Functions to implement

1. euclidean_distance(a, b)

Compute the Euclidean (L2) distance between two vectors.

  • Input: Two lists of numbers of equal length
  • Output: The straight-line distance

2. manhattan_distance(a, b)

Compute the Manhattan (L1) distance between two vectors.

  • Input: Two lists of numbers of equal length
  • Output: Sum of absolute differences

3. cosine_similarity(a, b)

Compute the cosine similarity between two vectors.

  • Input: Two lists of numbers of equal length
  • Output: A value between -1 and 1

4. cosine_distance(a, b)

Compute the cosine distance (1 - similarity).

  • Input: Two lists of numbers of equal length
  • Output: A value between 0 and 2

5. normalize(v)

Normalize a vector to unit length (L2 norm = 1).

  • Input: A list of numbers
  • Output: A normalized vector

Examples

euclidean_distance([0, 0], [3, 4])     # 5.0
manhattan_distance([0, 0], [3, 4])     # 7
cosine_similarity([1, 0], [1, 0])      # 1.0
cosine_similarity([1, 0], [0, 1])      # 0.0
cosine_distance([1, 0], [0, 1])        # 1.0
normalize([3, 4])                       # [0.6, 0.8]

Notes

  • Use math.sqrt for square root
  • Handle zero vectors appropriately
Run tests to see results
No issues detected