这是我的代码:
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
请帮忙!
答案 0 :(得分:0)
在函数hamming
中,
count,z = 0,int(a,2)^int(b,2)
看起来您将整数列表作为第一个参数(a
和b
)传递给函数int()
。第二个参数是你的明确基础。你不能这样做。
尝试将a
替换为''.join(str(el) for el in a)
,将b
替换为int2bin
。
或者,您可以将函数format(n, 'b')
替换为distanceTo
以直接获取二进制字符串。
答案 1 :(得分:0)
此代码计算两个可能很长的字符串的汉明距离。
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