Python - Hamming distance - 30 seconds of code Skip to content

Home

Hamming distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

To calculate the Hamming distance between two integers, you can use the XOR operator (^) to find the bit difference between the two numbers. Then, you can convert the result to a binary string using the bin() function.

Finally, you can convert the string to a list and use the count() method of the str class to count and return the number of 1s in it.

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

hamming_distance(2, 3) # 1

More like this

  • Collection · 8 articles

    Python Math

    Learn how to perform common mathematical operations in Python 3.6 with this article collection.

  • Python ·

    Binomial coefficient

    Calculate the number of ways to choose k items from n items without repetition and without order.

  • Python ·

    Prime factors of number

    Find the list of prime factors of a number, using a simple Python function.

Start typing a keyphrase to see matching articles.