Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
mak_thehammingdistance solution in Clear category for The Hamming Distance by makavely
from itertools import zip_longest
def checkio(n, m):
# Really short solution.
# Using xor we won't miss leading zeros
# in a shortest of a two strings representing
# given numbers in a binary form.
#return bin(n^m).count('1')
# Get the length of a longest strings
# representing given numbers in a binary form.
# Then format each of two numbers to a binary form
# filling shortest string with a leading zeros - '0{0}b'.
# Then zip corresponding bits from each number into a tuple.
# If elements of a tuple are not equal ('x != y'),
# then add 1 to sum (sum(1 for x, y...).
longest_string_length = max(len(format(n, 'b')), len(format(m, 'b')))
return sum(1 for x, y in zip(format(m, '0{0}b'.format(longest_string_length)), format(n, '0{0}b'.format(longest_string_length))) if x != y)
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"
July 17, 2017
Comments: