File tree 1 file changed +39
-0
lines changed
1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
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 ()
You can’t perform that action at this time.
0 commit comments