Notebook 1
The aim of this notebook is to create a Hash Table. Click here to access Notebook 1.
Task 1
The first cell creates a HashTable
class. Click Shift
+ Enter
to run this cell.
class HashTable:
def __init__(self):
self.size = 0
self.buckets = []
If you are not signed into Google, it will prompt you to do so.
Task 2
Add an insert
method to the HashTable
class.
def insert(self, key, value):
if not self.buckets:
self.buckets = [None] * 16
The insert
method takes an entry consisting of a key
and a value
. The first line of the method checks if the hash table has any buckets. If it doesn't, the method initializes the array with the capacity to store 16 elements.
Task 3
Rerun the cell (Shift
+ Enter
) so that the changes are recognized.
Task 4
Inside the second cell, create a HashTable
object.
inventory = HashTable()
Add the following entry into the HashTable
.
inventory = HashTable() inventory.insert("Banana", 2.99)
Run the cell.
Task 5
Inside the third cell, add code that displays the contents of our HashTable.
def displayInventory():
for index, item in enumerate(inventory.buckets):
print("\nBUCKET {0}".format(index))
print(item)
Run the cell
Task 6
Inside the fourth cell, call displayInventory()
.
displayInventory()
Run every cell by clicking Runtime | Run all.
Your final output should display a HashTable with 16 buckets.
BUCKET 0
None
BUCKET 1
None
BUCKET 2
None
...
Solution
You can access the solution code here.