Skip to content

Instantly share code, notes, and snippets.

@metula
Last active August 6, 2016 13:57
Show Gist options
  • Select an option

  • Save metula/8368843 to your computer and use it in GitHub Desktop.

Select an option

Save metula/8368843 to your computer and use it in GitHub Desktop.
import random
def hash_mod(key, mod, func=hash):
return func(key) % mod
def hash_table(m):
# initial hash table, m empty entries
return [[] for i in range(m)]
def contained(key, list_of_items):
""" checks if key is in list_of_items
returns location in list (if found), or None"""
for k in range(len(list_of_items)):
if key == list_of_items[k][0]:
return k # return index of candidate in list
return None
def find(key, table, func=hash):
""" finds an item in a hash table and returns it.
If the item is not found, returns None"""
mod = len(table)
i = hash_mod(key, mod, func)
list_of_items = table[i]
k = contained(key, list_of_items)
if k != None: # key exists in table
return list_of_items[k][1]
return None
def insert(key, value, table, func=hash):
""" inserts an item into a hash table. If key already
exists, the value is updated. Always returns None"""
mod = len(table)
i = hash_mod(key, mod, func)
list_of_items = table[i]
k = contained(key, list_of_items)
if k != None: # key exists in table
list_of_items[k] = (key, value)
else:
list_of_items.append((key, value))
return None
def delete(key, table, func=hash):
""" deletes an item from a hash table. """
raise NotImplemented
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment