MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / hamming_distance

Function hamming_distance

strings/hamming_distance.py:1–34  ·  view source on GitHub ↗

Calculate the Hamming distance between two equal length strings In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. https://en.wikipedia.org/wiki/Hamming_distance Args: s

(string1: str, string2: str)

Source from the content-addressed store, hash-verified

1def 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 Traceback (most recent call last):
22 ...
23 ValueError: String lengths must match!
24 """
25 if len(string1) != len(string2):
26 raise ValueError("String lengths must match!")
27
28 count = 0
29
30 for char1, char2 in zip(string1, string2):
31 if char1 != char2:
32 count += 1
33
34 return count
35
36
37if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected