Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Two for one solution in Clear category for The Hamming Distance by Krischtopp
def checkio(n, m):
"""
Explain from inside out:
"n ^ m" does binary XOR on n and m
"bin(n ^ m)" gives us binary representation as a string
"bin(n ^ m)[2:]" throws away the "0b" prefix
"(bit for bit in bin(n ^ m)[2:])" goes through the bits in the string via generator comprehension
"(int(bit) for bit in bin(n ^ m)[2:])" converts the bits into int so we can do math
"sum(int(bit) for bit in bin(n ^ m)[2:])" sums up all bits to calculate Hamming distance
"""
return sum(int(bit) for bit in bin(n ^ m)[2:])
def checkio_alternative(n, m):
"""
This also works, but uses modulo and integer division instead of converting back and forth between int and string
"""
bin_xor = n ^ m
hamming_distance = 0
while bin_xor:
hamming_distance += bin_xor % 2
bin_xor //= 2
return hamming_distance
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio(117, 17) == 3, "First example"
assert checkio(1, 2) == 2, "Second example"
assert checkio(16, 15) == 5, "Third example"
Jan. 26, 2016