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!
Try this implementation (
a
andb
are expected to be integers):Here I xor
a
andb
and get binary where ones represent differense betweena
andb
. Than I just count ones.In the function
hamming
,it looks like you are passing a list of integers as the first arguments (
a
andb
) to the functionint()
. 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 forb
.Alternatively you could replace the function
int2bin
withformat(n, 'b')
to get a binary string directly.This code calculates the Hamming Distance of two possibly quite long strings.