Given two strings
s1 = 'abcdef'
s2 = 'bbcdefg'
The goal is to find the Hamming distance between s1 and s2, not only counting the difference of varying characters, but also any additional characters to be added to the final count. In s2 the first character is 'b', not 'a' like in s1, so that would be plus one to the count. However, s2 also has 'g' where s1 does not, making s1 one character longer in length, causing their Hamming distance count to be equal to 2.
Ideally the code would be one line long.
What I have so far is:
def hamming_distance(s1, s2):
return sum(c1 != c2 for c1, c2 in zip(s1, s2))
hamming_distance('abcdef', 'bbcdefg')
1
I'm using python version 3.8.5
You could try itertools.zip_longest to avoid zip() to stop on the shortest string.
from itertools import zip_longest
def hamming_distance(s1, s2):
return sum(c1 != c2 for c1, c2 in zip_longest(s1, s2))
hamming_distance('abcdef', 'bbcdefg') # 2
hamming_distance('book', 'tooth') # 3