Python中两个字符串之间的汉明距离 [英] Hamming Distance Between Two Strings In Python

查看:57
本文介绍了Python中两个字符串之间的汉明距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,我需要找到两个字符串之间的汉明距离:

I'm new to Python and I need to find the Hamming distance between two strings:

chaine1 = 6fb17381822a6ca9b02153d031d5d3da

chaine2 = a242eace2c57f7a16e8e872ed2f2287d

XOR 功能没用,我在网上搜索也不是很成功.

The XOR function didn't work, and my search on the web was not very successful.

我试图修改我在网上找到的东西,但有一些无效的语法...:

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))

你得到 Invalid syntax: ... 的原因可能是你没有任何缩进,这在 Python 中是必需的.

The reason why you get Invalid syntax: ... is probably you don't have any indentations, which are required in Python.

这篇关于Python中两个字符串之间的汉明距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆