Skip to content

Instantly share code, notes, and snippets.

@thiagopnts
Created March 14, 2012 15:13
Show Gist options
  • Save thiagopnts/2037141 to your computer and use it in GitHub Desktop.
Save thiagopnts/2037141 to your computer and use it in GitHub Desktop.
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
class HashMap:
def __init__(self):
self.__size = 50
self.__table = [[] for i in range(self.__size)]
def put(self, key, value):
self[key] = value
def get(self, key):
for i in range(self.__size):
for j in range(len(self.__table[i])):
node = self.__table[i][j]
if node.key == key:
return node.value
raise Exception('key dont exists')
def __setitem__(self, key, value):
i = self.__hash(key)
if len(self.__table[i]) > 0:
for node in self.__table[i]:
if node.key == key:
node.value = value
return
self.__table[i].append(Node(key, value))
def __hash(self, key):
val = 4
for char in key:
val += ord(char)
return val%self.__size
def keys(self):
return [node.key for list in self.__table for node in list if node]
def values(self):
return [node.value for list in self.__table for node in list if node]
def clear(self):
self.__table = [[] for i in range(self.__size)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment