30秒学会 Python 片段 · 2023年11月13日

30秒学会 Python 片段 – Hamming distance

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

翻译自:https://www.30secondsofcode.org/python/s/hamming-distance