From bfdb98c7374fb4f60c6b10be89729df4ab2ca60a Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Sun, 17 Jan 2021 13:04:06 +0200 Subject: [PATCH] Add hamming_distance --- snippets/hamming_distance.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 snippets/hamming_distance.md diff --git a/snippets/hamming_distance.md b/snippets/hamming_distance.md new file mode 100644 index 000000000..9740736fa --- /dev/null +++ b/snippets/hamming_distance.md @@ -0,0 +1,19 @@ +--- +title: hamming_distance +tags: 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 `1`s in it. + +```py +def hamming_distance(a, b): + return list(bin(a ^ b)).count('1') +``` + +```py +hamming_distance(2, 3) # 1 +```