input 2 integers and get binary, brgc, and hamming distance

独自空忆成欢 提交于 2019-12-12 19:00:49

问题


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

here is my code:

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

output should look like

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

please help!


回答1:


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

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

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




回答2:


In the function hamming,

count,z = 0,int(a,2)^int(b,2)

it looks like you are passing a list of integers as the first arguments (a and b) to the function int(). the second argument is your explicit base. you cant do this.

Try replacing a with ''.join(str(el) for el in a) and the same for b.

Alternatively you could replace the function int2bin with format(n, 'b') to get a binary string directly.




回答3:


This code calculates the Hamming Distance of two possibly quite long strings.

def hammingDist(s1,s2):
if type(s1) is str: s1=s1.encode()
if type(s2) is str: s2=s2.encode()

count=0
for b1,b2 in zip(s1,s2):
    a=b1^b2
    while a>0:
        count+= a & 1
        a=a >> 1
return count


来源:https://stackoverflow.com/questions/33663676/input-2-integers-and-get-binary-brgc-and-hamming-distance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!