简体   繁体   English

Python中两个字符串之间的汉明距离

[英]Hamming Distance Between Two Strings In Python

I'm new to Python and I need to find the Hamming distance between two strings:我是 Python 新手,我需要找到两个字符串之间的汉明距离:

chaine1 = 6fb17381822a6ca9b02153d031d5d3da

chaine2 = a242eace2c57f7a16e8e872ed2f2287d

The XOR function didn't work, and my search on the web was not very successful. XOR 功能不行,我在网上搜索也不是很成功。

I tried to modify something I found on the web, but there's some invalid syntax...:我试图修改我在网上找到的东西,但有一些无效的语法......:

assert len (chaine1) == len(chaine2)

return sum(chaine1 != chaine2 for chaine1, chaine2 in zip(chaine1, chaine2))


if __name__=="__main__":    
chaine1 = hashlib.md5("chaine1".encode()).hexdigest()

chaine2 = hashlib.md5("chaine2".encode()).hexdigest()
print hamming_distance(chaine1, chaine2)

Any ideas on how I could proceed?关于我如何进行的任何想法? Thanks!谢谢!

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.你得到Invalid syntax: ...原因可能是你没有任何缩进,这在 Python 中是必需的。

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.让我们来解决它。

def hamming(s1,s2):
result=0
if len(s1)!=len(s2):
    print("String are not equal")
else:
    for x,(i,j) in enumerate(zip(s1,s2)):
        if i!=j:
            print(f'char not math{i,j}in {x}')
            result+=1
return result
s1="rover"
s2="river"
print(hamming(s1,s2))

Result: char not match ('o', 'i') in 1结果:char not match ('o', 'i') in 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM