-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChainingHashTable.py
More file actions
68 lines (59 loc) · 2.42 KB
/
ChainingHashTable.py
File metadata and controls
68 lines (59 loc) · 2.42 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""
Course: CS2302 Data Structures
Author: Javier Navarro
Assignment: Lab 4 Option B
Instructor: Diego Aguirre
TA: Manoj Saha
Last modified: 11/13/18
Purpose: Hold contents for a hash table class
"""
# HashTable class using chaining.
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, item):
# get the bucket list where this item will go.
bucket = hash(item) % len(self.table)
bucket_list = self.table[bucket]
# insert the item to the end of the bucket list.
bucket_list.append(item)
# 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]
# search for the key in the bucket list
if key in bucket_list:
# find the item's index and return the item that is in the bucket list.
item_index = bucket_list.index(key)
return bucket_list[item_index]
else:
# the key is not found.
return None
def search_comparisons(self, key):
# get the bucket list where this key would be.
bucket = hash(key) % len(self.table)
bucket_list = self.table[bucket]
# search for the key in the bucket list
if key in bucket_list:
# find the item's index and return the item that is in the bucket list.
item_index = bucket_list.index(key)
return item_index + 1
else:
# the key is not found.
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.
if key in bucket_list:
bucket_list.remove(key)