pysnippets.strings.hamming_distance
Hamming distance between strings
hamming_distance(a: str, b: str) -> int
Count the positions at which two equal-length strings differ.
How many characters changed between two codes, sequences or hashes of the same length?
hamming_distance.py✓ ruff · mypy --strict
def hamming_distance(a: str, b: str) -> int:
"""Return how many positions differ between two equal-length strings."""
if len(a) != len(b):
raise ValueError(f"strings must have equal length, got {len(a)} and {len(b)}")
return sum(x != y for x, y in zip(a, b, strict=True))- True counts as 1 in sum()
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> hamming_distance("karolin", "kathrin")3passed on Python 3.11 to 3.14: >>> hamming_distance("", "")0passed on Python 3.11 to 3.14: >>> hamming_distance("abc", "ab")Traceback (most recent call last):...ValueError: strings must have equal length, got 3 and 2Edit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).
python 3.14 · in your browser
Loading Python 3.14 in your browser (≈7 MB, cached after the first time)…
Tab inserts four spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the examples.
How it works
zip(..., strict=True)walks both strings in step.x != yis a bool, andsumcounts eachTrueas 1.- Different lengths raise
ValueError: Hamming distance isn’t defined for them.
For integers, count the differing bits instead:
python
(a ^ b).bit_count() # Python 3.10+Complexity: O(n) time, O(1) space
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from pysnippets.strings.hamming_distance import hamming_distanceNo dependencies: copy hamming_distance.py into your project, or clone the repo.Adapted from hamming-distance in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Rewritten for strings; the integer version is shown below. Suggest an edit.