forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* implement hash * fix flake8 error * Update hashes/djb2.py * Update hashes/djb2.py * Long lines * def djb2(s: str) -> int: Co-authored-by: Christian Clauss <[email protected]>
- Loading branch information
1 parent
924ef9b
commit 62f7561
Showing
1 changed file
with
35 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,35 @@ | ||
""" | ||
This algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c | ||
Another version of this algorithm (now favored by Bernstein) uses xor: | ||
hash(i) = hash(i - 1) * 33 ^ str[i]; | ||
First Magic constant 33: | ||
It has never been adequately explained. | ||
It's magic because it works better than many other constants, prime or not. | ||
Second Magic Constant 5381: | ||
1. odd number | ||
2. prime number | ||
3. deficient number | ||
4. 001/010/100/000/101 b | ||
source: http://www.cse.yorku.ca/~oz/hash.html | ||
""" | ||
|
||
|
||
def djb2(s: str) -> int: | ||
""" | ||
Implementation of djb2 hash algorithm that | ||
is popular because of it's magic constants. | ||
>>> djb2('Algorithms') | ||
3782405311 | ||
>>> djb2('scramble bits') | ||
1609059040 | ||
""" | ||
hash = 5381 | ||
for x in s: | ||
hash = ((hash << 5) + hash) + ord(x) | ||
return hash & 0xFFFFFFFF |