File tree 1 file changed +35
-0
lines changed
1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ This algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c
3
+ Another version of this algorithm (now favored by Bernstein) uses xor:
4
+ hash(i) = hash(i - 1) * 33 ^ str[i];
5
+
6
+ First Magic constant 33:
7
+ It has never been adequately explained.
8
+ It's magic because it works better than many other constants, prime or not.
9
+
10
+ Second Magic Constant 5381:
11
+
12
+ 1. odd number
13
+ 2. prime number
14
+ 3. deficient number
15
+ 4. 001/010/100/000/101 b
16
+
17
+ source: http://www.cse.yorku.ca/~oz/hash.html
18
+ """
19
+
20
+
21
+ def djb2 (s : str ) -> int :
22
+ """
23
+ Implementation of djb2 hash algorithm that
24
+ is popular because of it's magic constants.
25
+
26
+ >>> djb2('Algorithms')
27
+ 3782405311
28
+
29
+ >>> djb2('scramble bits')
30
+ 1609059040
31
+ """
32
+ hash = 5381
33
+ for x in s :
34
+ hash = ((hash << 5 ) + hash ) + ord (x )
35
+ return hash & 0xFFFFFFFF
You can’t perform that action at this time.
0 commit comments