输入2个整数并获取二进制,brgc和汉明距离 [英] input 2 integers and get binary, brgc, and hamming distance

查看:115
本文介绍了输入2个整数并获取二进制,brgc和汉明距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了汉明距离,我已经拥有了一切.我不断收到错误消息"int()无法使用显式基数转换非字符串"

I've got everything except hamming distance. I keep getting the error "int() can't convert non-string with explicit base"

这是我的代码:

def int2bin(n):                                
    if n:
        bits = []
        while n:
            n,remainder = divmod(n, 2)
            bits.insert(0, remainder)
        return bits
    else: return [0]

def bin2gray(bits):                  
    return bits[:1] + [i ^ ishift for i, ishift in zip(bits[:-1], bits[1:])]

def hamming(a,b):                        
    assert len(a) == len(b)
    count,z = 0,int(a,2)^int(b,2)
    while z:
        count += 1
        z &= z-1 
    return count

def main():
    a = int(input("Positive integer 1: "))        
    b = int(input("Positive integer 2: "))
    print('int:%2i    binary:%12r    BRGC:%12r' %    
          ( a,
            int2bin(a),
        bin2gray(int2bin(a))
           ))
    print('int:%2i    binary:%12r    BRGC:%12r' %
          ( b,
            int2bin(b),
        bin2gray(int2bin(b))
           ))
    print('hamming|%2     %12r        &12r' %
          (hamming(int2bin(a),int2bin(b)),
           hamming(bin2gray(int2bin(a)),bin2gray(int2bin(b)))
           ))

main()

输出应该像

int: 5 binary: [1, 0, 1] brgc: [1, 1, 1]    
int: 6 binary: [1, 1, 0] brgc: [1, 0, 1]    
hamming            2               1

请帮助!

推荐答案

尝试此实现(ab应该是整数):

Try this implementation (a and b are expected to be integers):

def hamming(a, b):
    return bin(a^b).count('1')

在这里我将ab进行异或运算,并得到二进制文件,其中一个表示ab之间的差异.比我只算一个.

Here I xor a and b and get binary where ones represent differense between a and b. Than I just count ones.

这篇关于输入2个整数并获取二进制,brgc和汉明距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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