-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashtable.py
51 lines (40 loc) · 1.22 KB
/
hashtable.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Hashtable:
def __init__(self):
self.table_size = 100
self.table = [None] * self.table_size
def hash(self, key):
hash_value = 0
for char in key:
hash_value = (hash_value + ord(char)) % self.table_size
return hash_value
def set(self, key, value):
index = self.hash(key)
if not self.table[index]:
self.table[index] = []
for entry in self.table[index]:
if entry[0] == key:
entry[1] = value
self.table[index].append((key, value))
def get(self, key):
index = self.hash(key)
if not self.table[index]:
return None
for entry in self.table[index]:
if entry[0] == key:
return entry[1]
return None
def has(self, key):
index = self.hash(key)
if not self.table[index]:
return False
for entry in self.table[index]:
if entry[0] == key:
return True
return False
def keys(self):
keys = []
for bucket in self.table:
if bucket:
for entry in bucket:
keys.append(entry[0])
return keys