-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hash.py
53 lines (46 loc) · 1.91 KB
/
Hash.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
52
53
class ChainingHashTable:
# Constructor with optional initial capacity parameter.
# Assigns all buckets with an empty list.
def __init__(self, initial_capacity=10):
# initialize the hash table with empty bucket list entries.
self.table = []
for i in range(initial_capacity):
self.table.append([])
# Inserts a new item into the hash table.
def insert(self, PackageID, Package): # does both insert and update
# get the bucket list where this item will go.
bucket = hash(PackageID) % len(self.table)
bucket_list = self.table[bucket]
# update key if it is already in the bucket
for kv in bucket_list:
# print (key_value)
if kv[0] == PackageID:
kv[1] = Package
return True
# if not, insert the item to the end of the bucket list.
key_value = [PackageID, Package]
bucket_list.append(key_value)
return True
# Searches for an item with matching key in the hash table.
# Returns the item if found, or None if not found.
def search(self, key):
# get the bucket list where this key would be.
bucket = hash(key) % len(self.table)
bucket_list = self.table[bucket]
# print(bucket_list)
# search for the key in the bucket list
for kv in bucket_list:
# print (key_value)
if kv[0] == key:
return kv[1] # value
return None
# Removes an item with matching key from the hash table.
def remove(self, key):
# get the bucket list where this item will be removed from.
bucket = hash(key) % len(self.table)
bucket_list = self.table[bucket]
# remove the item from the bucket list if it is present.
for kv in bucket_list:
# print (key_value)
if kv[0] == key:
bucket_list.remove([kv[0], kv[1]])