Skip to content

Commit 89fc7bf

Browse files
author
Sedat Aybars Nazlica
authored
Add hamming distance (TheAlgorithms#6194)
* Add hamming distance * Fix doctest * Refactor * Raise ValueError when string lengths are different
1 parent e5d1ff2 commit 89fc7bf

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

strings/hamming_distance.py

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
def hamming_distance(string1: str, string2: str) -> int:
2+
"""Calculate the Hamming distance between two equal length strings
3+
In information theory, the Hamming distance between two strings of equal
4+
length is the number of positions at which the corresponding symbols are
5+
different. https://en.wikipedia.org/wiki/Hamming_distance
6+
7+
Args:
8+
string1 (str): Sequence 1
9+
string2 (str): Sequence 2
10+
11+
Returns:
12+
int: Hamming distance
13+
14+
>>> hamming_distance("python", "python")
15+
0
16+
>>> hamming_distance("karolin", "kathrin")
17+
3
18+
>>> hamming_distance("00000", "11111")
19+
5
20+
>>> hamming_distance("karolin", "kath")
21+
ValueError: String lengths must match!
22+
"""
23+
if len(string1) != len(string2):
24+
raise ValueError("String lengths must match!")
25+
26+
count = 0
27+
28+
for char1, char2 in zip(string1, string2):
29+
if char1 != char2:
30+
count += 1
31+
32+
return count
33+
34+
35+
if __name__ == "__main__":
36+
37+
import doctest
38+
39+
doctest.testmod()

0 commit comments

Comments
 (0)