-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash_table.py
More file actions
40 lines (33 loc) · 1.18 KB
/
hash_table.py
File metadata and controls
40 lines (33 loc) · 1.18 KB
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
# code for Hashtable from W-2_ChainingHashTable_zyBooks_Key-Value_CSV_Greedy.py
class ChainingHashTable:
def __init__(self, initial_capacity=10):
self.table = []
for i in range(initial_capacity):
self.table.append([])
# insert or update package with package id as key
def insert(self, key, item):
bucket = hash(key) % len(self.table)
bucket_list = self.table[bucket]
for kv in bucket_list:
if kv[0] == key:
kv[1] = item # Update the key if it exists
return True
bucket_list.append([key, item])
return True
# search for a package by key
def search(self, key):
bucket = hash(key) % len(self.table)
bucket_list = self.table[bucket]
for kv in bucket_list:
if kv[0] == key:
return kv[1] # return the item if its found
return None
# remove a package by key
def remove(self, key):
bucket = hash(key) % len(self.table)
bucket_list = self.table[bucket]
for kv in bucket_list:
if kv[0] == key:
kv[1] = None
return True
return False