Click4Ai

34.

Easy

Write a function cosine_similarity(v1, v2) that computes the cosine similarity between two vectors. Cosine similarity measures how similar two vectors are by the cosine of the angle between them.

**Formula:** cos_sim = dot(v1, v2) / (||v1|| * ||v2||)

Example:

Input: v1 = [1, 2, 3], v2 = [4, 5, 6]

Output: 0.9746

**Explanation:** dot=32, ||v1||=3.7417, ||v2||=8.7749 → 32/(3.7417*8.7749) = 0.9746

Constraints:

  • Both vectors have the same length, non-zero
  • Return a float rounded to 4 decimal places
  • Result is always between -1 and 1
  • Test Cases

    Test Case 1
    Input: [1, 2, 3], [4, 5, 6]
    Expected: 0.9746
    Test Case 2
    Input: [1, 0], [0, 1]
    Expected: 0.0
    Test Case 3
    Input: [1, 1], [1, 1]
    Expected: 1.0
    + 2 hidden test cases