Hamming Distance Between Two Strings In Python
I'm new to Python and I need to find the Hamming distance between two strings: chaine1 = 6fb17381822a6ca9b02153d031d5d3da chaine2 = a242eace2c57f7a16e8e872ed2f2287d The XOR func
Solution 1:
Following is a program calculating hamming distance using two different ways.
import hashlib
def hamming_distance(chaine1, chaine2):
return sum(c1 != c2 for c1, c2 in zip(chaine1, chaine2))
def hamming_distance2(chaine1, chaine2):
return len(list(filter(lambda x : ord(x[0])^ord(x[1]), zip(chaine1, chaine2))))
if __name__=="__main__":
chaine1 = hashlib.md5("chaine1".encode()).hexdigest()
chaine2 = hashlib.md5("chaine2".encode()).hexdigest()
#chaine1 = "6fb17381822a6ca9b02153d031d5d3da"
#chaine2 = "a242eace2c57f7a16e8e872ed2f2287d"
assert len(chaine1) == len(chaine2)
print(hamming_distance(chaine1, chaine2))
print(hamming_distance2(chaine1, chaine2))
The reason why you get Invalid syntax: ...
is probably you don't have any indentations, which are required in Python.
Solution 2:
First should the definition of Hamming Distance between two string.
The hamming distance between two strings of equal length is the number of positions at which these strings vary. In more technical terms, it is a measure of the minimum number of changes required to turn one string into another.
Let's get a solution of it.
defhamming(s1,s2):
result=0iflen(s1)!=len(s2):
print("String are not equal")
else:
for x,(i,j) inenumerate(zip(s1,s2)):
if i!=j:
print(f'char not math{i,j}in {x}')
result+=1return result
s1="rover"
s2="river"print(hamming(s1,s2))
Result: char not match ('o', 'i') in 1
Post a Comment for "Hamming Distance Between Two Strings In Python"