Last active
March 1, 2016 16:23
-
-
Save zshihang/22aa5374089681061e2d to your computer and use it in GitHub Desktop.
Simple Implementation of HashTable in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HashTable(object): | |
def __init__(self, size=100): | |
self._size=size | |
self._table=[[] for i in range(self._size)] | |
def get(self, key): | |
hash = self._hash(key) | |
bucket = self._table[hash] | |
for x in bucket: | |
if x[0] == key: | |
return x[1] | |
return None | |
def put(self, key, value): | |
if key is None or value is None: | |
raise ValueError('Bad Key or Value') | |
hash = self._hash(key) | |
bucket = self._table[hash] | |
isExist = False | |
for x in bucket: | |
if x[0] = key | |
x[1] = value | |
isExist = True | |
if not isExist: | |
bucket.append((key, value)) | |
def _hash(self, key): | |
string = str(key) | |
sum = 0 | |
for c in string: | |
sum += ord(c) | |
return sum % self._size |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment