Skip to content
scipython.com

P2.4.2The Hamming distance between strings

The Hamming distance between two equal-length strings is the number of positions at which the characters are different. Write a Python routine to calculate the Hamming distance between two strings, s1 and s2.

Show solution

One possibility is to loop over an index to both strings:

s1, s2 = 'noiseless', 'nuisances'

h = 0
for i in range(len(s1)):
    if s1[i] != s2[i]:
        h += 1

print('The Hamming distance between the strings "{:s}" and "{:s}" is {:d}.'
        .format(s1, s2, h))

However, since we need to loop over two sequences at the same time, the more Pythonic solution is to zip them:

s1, s2 = 'noiseless', 'nuisances'

h = 0
for c1, c2 in zip(s1, s2):
    if c1 != c2:
        h += 1

print('The Hamming distance between the strings "{:s}" and "{:s}" is {:d}.'
        .format(s1, s2, h))

zip(s1,s2) produces the sequence of character pairs taken from the strings: ('n', 'n'), ('o', 'u'), ...