Files
30-seconds-of-code/snippets/hamming-distance.md
Angelos Chalaris f6a215e9e3 Kebab file names
2023-04-27 22:00:06 +03:00

552 B

title, tags, cover, firstSeen, lastUpdated
title tags cover firstSeen lastUpdated
Hamming distance math tulips-and-reeds 2021-01-17T13:04:06+02:00 2021-02-18T14:22:25+02:00

Calculates the Hamming distance between two values.

  • Use the XOR operator (^) to find the bit difference between the two numbers.
  • Use bin() to convert the result to a binary string.
  • Convert the string to a list and use count() of 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