如何解决我的 Python 汉明距离代码有问题吗?
我正在尝试在 Python 中实现 Hamming distance。汉明距离通常用于测量两个码字之间的距离。该操作只是执行异或。例如,如果我们有代码字 10011101 和 10111110,那么它们的异或将是 00100011,并且汉明距离被称为 1 + 1 + 1 = 3。
我的代码如下:
def hamming_distance(codeword1,codeword2):
"""Calculate the Hamming distance between two bit strings"""
assert len(codeword1) == len(codeword2)
x,y = int(codeword1,2),int(codeword2,2) # '2' specifies that we are reading a binary number
count,z = 0,x^y
while z:
count += 1
z &= z - 1
return count
def checking_codewords(codewords,received_data):
closestdistance = len(received_data) # set default/placeholder closest distance as the maximum possible distance.
closestCodeword = received_data # default/placeholder closest codeword
for i in codewords:
if(hamming_distance(i,received_data) < closestdistance):
closestCodeword = i
closestdistance = hamming_distance(i,received_data)
return closestCodeword
print(checking_codewords(['1010111101','0101110101','1110101110','0000000110','1100101001'],'0001000101'))
hamming_distance(codeword1,codeword2)
以二进制值的形式获取两个输入参数 codeword1
和 codeword2
,并返回两个输入码字之间的汉明距离。
checking_codewords(codewords,received_data)
应该确定正确的代码字 IFF 接收数据中有任何错误(即,输出是正确的代码字串)。虽然,如您所见,我还没有添加“IFF 收到的数据中有任何错误”部分。
我刚刚用一组示例测试了 checking_codewords
函数,除了一个示例外,它似乎对所有示例都能正常工作。当我使用代码字集 ['1010111101','1100101001']
和接收到的数据 '0001000101'
时,输出为 0101110101
,这显然是不正确的。我的代码有问题吗,或者 0101110101
实际上是正确的并且示例有问题?或者这只是接收数据没有错误的情况,所以我的代码错过了?
解决方法
在我看来,不清楚为什么您的算法将初始字符串转换为整数以进行按位差分。
我的意思是,在断言相等长度之后,您可以使用 zip 函数简单地计算差异:
sum([c1!=c2 for c1,c2 in zip(codeword1,codeword2)])
对于 sum 函数,python 考虑 True==1,False==0。
对您的代码做一些简化:
def hamming_distance(codeword1,codeword2):
"""Calculate the Hamming distance between two bit strings"""
assert len(codeword1) == len(codeword2)
return sum([c1!=c2 for c1,codeword2)])
def checking_codewords(codewords,received_data):
min_dist,min_word = min([(hamming_distance(i,received_data),received_data) for i in codewords])
return min_word
print(checking_codewords(['1010111101','0101110101','1110101110','0000000110','1100101001'],'0001000101'))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。