Skip to content

Commit 633c245

Browse files
committed
add hash表实现
1 parent 66f6857 commit 633c245

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

hashtable.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# -*- coding: utf-8 -*-
2+
# @Author: lock
3+
# @Date: 2017-12-15 00:49:17
4+
# @Last Modified by: lock
5+
# @Last Modified time: 2017-12-15 01:00:13
6+
class Item(object):
7+
8+
def __init__(self, key, value):
9+
self.key = key
10+
self.value = value
11+
12+
13+
class HashTable(object):
14+
15+
def __init__(self, size):
16+
self.size = size
17+
self.table = [[] for _ in xrange(self.size)]
18+
19+
def hash_function(self, key):
20+
return key % self.size
21+
22+
def set(self, key, value):
23+
hash_index = self.hash_function(key)
24+
for item in self.table[hash_index]:
25+
if item.key == key:
26+
item.value = value
27+
return
28+
self.table[hash_index].append(Item(key, value))
29+
30+
def get(self, key):
31+
hash_index = self.hash_function(key)
32+
for item in self.table[hash_index]:
33+
if item.key == key:
34+
return item.value
35+
return None
36+
37+
def remove(self, key):
38+
hash_index = self.hash_function(key)
39+
for i, item in enumerate(self.table[hash_index]):
40+
if item.key == key:
41+
del self.table[hash_index][i]
42+
43+
if __name__ == '__main__':
44+
hash_table = HashTable(5);
45+
hash_table.set(1,'x')
46+
hash_table.set(1,'m')
47+
hash_table.set(2,'y')
48+
hash_table.set(3,'z')
49+
print hash_table.get(1)
50+
print hash_table.get(2)
51+
print hash_table.get(3)

0 commit comments

Comments
 (0)