Files
30-seconds-of-code/snippets/hamming_distance.md
Isabelle Viktoria Maciohsek bfdb98c737 Add hamming_distance
2021-01-17 13:04:06 +02:00

480 B

title, tags
title tags
hamming_distance math,intermediate

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 list.count() to count and return the number of 1s in it.
def hamming_distance(a, b):
  return list(bin(a ^ b)).count('1')
hamming_distance(2, 3) # 1