【问题标题】:Is there something wrong with my Python Hamming distance code?我的 Python 汉明距离代码有问题吗?
【发布时间】:2021-03-20 07:42:46
【问题描述】:

我正在尝试在 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)以二进制值的形式获取codeword1codeword2这两个输入参数,返回两个输入码字之间的汉明距离。

checking_codewords(codewords, received_data) 应该确定正确的码字 IFF 接收到的数据有任何错误(即,输出是更正的码字串)。虽然如您所见,我还没有添加“IFF 接收到的数据有任何错误”部分。

我刚刚用一组示例测试了checking_codewords 函数,它似乎对除一个之外的所有示例都正常工作。当我使用代码字集['1010111101', '0101110101', '1110101110', '0000000110', '1100101001'] 和接收到的数据'0001000101' 时,输出是0101110101,这显然是不正确的。我的代码是否有问题,或者0101110101 实际上是正确的并且示例有问题?或者这只是接收到的数据没有错误的情况,所以我的代码错过了它?

【问题讨论】:

  • 您是否尝试跟踪该示例输入的代码操作?例如,hamming_distance('0101110101', '0001000101') 的结果是什么?那是对的吗?其他码字呢?现在,checking_codewords 中的循环是否运行正常? “或者这只是接收到的数据没有错误的情况,所以我的代码错过了它?”那么,您难道不应该知道正确答案应该是什么吗?尝试手动解决。如果你不能为一个玩具示例做到这一点,你怎么能期望编写正确的代码?
  • @KarlKnechtel 是的,我只是在发布此评论后才看到您的评论。我现在正在阅读。
  • 作为提示:问题出在您正在重新发明的轮子上。如果您检查整数的内置方法 (dir(int)),您应该会看到一些让您的生活更轻松的东西。
  • @KarlKnechtel 感谢您的提示。我猜你指的“轮子”是hamming_distance

标签: python hamming-distance


【解决方案1】:

在我看来,不清楚为什么您的算法将初始字符串转换为 整数 以进行按位差分。

我的意思是,在断言相等长度之后,您可以使用 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,c2 in zip(codeword1,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'))

【讨论】:

    猜你喜欢
    • 2012-09-26
    • 1970-01-01
    • 2017-09-10
    • 2015-05-30
    • 2014-09-12
    • 2015-03-21
    • 2012-03-10
    • 2014-01-28
    • 1970-01-01
    相关资源
    最近更新 更多