forked from Chalarangelo/30-seconds-of-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
19 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 | ||
``` |