Skip to content

Instantly share code, notes, and snippets.

@edwintcloud
Created April 29, 2019 18:24
Show Gist options
  • Save edwintcloud/ae8fd068d7cbe9935c48904adf786741 to your computer and use it in GitHub Desktop.
Save edwintcloud/ae8fd068d7cbe9935c48904adf786741 to your computer and use it in GitHub Desktop.
Hash Table Part 3
def contains(self, key):
"""Return True if the key is found in the HashTable,
otherwise return False"""
# get the slot (linked_list) the key belongs to
# using our _get_hash_index function
slot = self.slots[self._get_hash_index(key)]
# look for key in linked list
# if found return True, otherwise return False
if slot.find_by_key(key) is not None:
return True
else:
return False
def get(self, key):
"""Return data found by given key in the HashTable,
return None if key is not found"""
# get the slot (linked_list) the key belongs to
# using our _get_hash_index function
slot = self.slots[self._get_hash_index(key)]
# find key in linked list and return
return slot.find_by_key(key)
def set(self, key, value):
"""Add an item to the HashTable by key and value"""
# get the slot (linked_list) the key belongs to
# using our _get_hash_index function
slot = self.slots[self._get_hash_index(key)]
# if the item isn't already in the hash table,
# increment size (delete item if it is)
if not slot.delete_by_key(key):
self.size += 1
# append item to end of slot (linked list)
slot.append((key, value))
# if load factor exceeds 0.66, resize
if (self.size / len(self.slots)) > 0.66:
self._resize()
def delete(self, key):
"""Remove an item from the HashTable by key or raise KeyError if key
is not found in the HashTable"""
# get the slot (linked_list) the key belongs to
# using our _get_hash_index function
slot = self.slots[self._get_hash_index(key)]
# delete item or throw key error if item was not found
if slot.delete_by_key(key):
self.size -= 1
else:
raise KeyError('Key {} not found in HashTable'.format(key))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment