Skip to content

Commit 6232f15

Browse files
committed
哈希函数
1 parent 7aa0f81 commit 6232f15

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

hash_function.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
"""
5+
@param key: A String you should hash
6+
@param HASH_SIZE: An integer
7+
@return an integer
8+
"""
9+
def hashCode(self, key, HASH_SIZE):
10+
# write your code here
11+
x = 0
12+
for i in xrange(len(key)):
13+
x += ord(key[i]) * self.fastPower(33, HASH_SIZE, len(key) - 1 - i)
14+
return x % HASH_SIZE
15+
16+
def fastPower(self, a, b, n): # 参考fast_power.py实现快速取模
17+
# write your code here
18+
if n == 0:
19+
return 1 % b
20+
if 1 == n:
21+
return a % b
22+
x = self.fastPower(a, b, n / 2)
23+
if n % 2 == 1:
24+
return (((x * x) % b) * a) % b
25+
else:
26+
return (x * x) % b

0 commit comments

Comments
 (0)