Neural Mastery
← Practice
Binary Quantization and Hamming Distanceeasy

Binary Quantization and Hamming Distance

easy RAG & Retrieval 15 min

NumPy allowed · plain Python earns 10 bonus points

RAG step 1/4

A query retrieves context

Embedding similarity ranks the documents before generation.
Open lesson →
01query
02embed
03retrieve
04context
What is RAG?→ embed →top context
retrieval.md44%
rag-systems.md33%
agents.md24%

Cosine-like similarity scores ranked before context assembly

Implement sign-based binary quantization, a cheap first-pass filter real vector databases use before exact re-ranking.

Task

Implement binary_quantize_hamming(a, b). Quantize each vector to a bit per dimension (1 if the component is >= 0, else 0), then return the Hamming distance (count of differing bits) between the two quantized vectors.

Function Signature

binary_quantize_hamming(a: list[float], b: list[float]) -> int

Examples

Example 1: identical sign patterns
Input: a = [1, -2, 3] b = [0.5, -0.1, 4]
Output: 0
Example 2: fully opposite signs
Input: a = [1, 1, 1] b = [-1, -1, -1]
Output: 3
Example 3: zero counts as positive
Input: a = [0, -1] b = [0, 1]
Output: 1

Constraints

  • len(a) == len(b)
  • 1 <= len(a) <= 4096
Python3Saved ✓
def binary_quantize_hamming(a: list[float], b: list[float]) -> int:
# Your implementation here
pass

Case 1: identical sign patterns
Input: a = [1, -2, 3] b = [0.5, -0.1, 4]
Expected: 0
Case 2: fully opposite signs
Input: a = [1, 1, 1] b = [-1, -1, -1]
Expected: 3
Case 3: zero counts as positive
Input: a = [0, -1] b = [0, 1]
Expected: 1