HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTip

Hamming distance

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
hammingpythondistance

Problem

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.

Solution

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

hamming_distance(2, 3) # 1


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.

Code Snippets

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

hamming_distance(2, 3) # 1

Context

From 30-seconds-of-code: hamming-distance

Revisions (0)

No revisions yet.