Last active
February 3, 2017 20:11
-
-
Save anbnyc/02f15c227bc7b1ec4de2d0d84e55d921 to your computer and use it in GitHub Desktop.
Implementation of hash table
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
### Implementation of Hash Table | |
# Methods: insert, search, delete | |
# Language: Python 2 or Python 3 | |
import json | |
## initialize hash_table | |
# arg n (int): length of the hash table | |
class hash_table(object): | |
def __init__(self,n=10): | |
self.length = n | |
self.buckets = [None]*n | |
## print out the JSON of the hash table | |
# no args | |
def __str__(self): | |
return json.dumps(self.buckets,indent=2) | |
## get hash of key mod (length of hash table) | |
# arg key (string): value to get hash of | |
def hash(self,key): | |
return hash(key) % self.length | |
## insert a new key,value pair to the hash table | |
# arg key (string): key of new pair | |
# arg value (string or num): value of new pair | |
def insert(self,key,value): | |
bucket = self.hash(key) | |
if self.buckets[bucket] == None: | |
self.buckets[bucket] = list() | |
self.buckets[bucket].append({"key": key, "value": value}) | |
## find a key,value pair from hash table | |
# arg key (string): key to find | |
def search(self,key): | |
bucket = self.buckets[self.hash(key)] | |
for item in bucket: | |
if key == item["key"]: | |
return item | |
return "Item '"+key+"' not in table" | |
## delete a key,value pair from hash table | |
# arg key (string) | |
def delete(self,key): | |
bucket = self.hash(key) | |
# self.buckets[bucket] = [item for item in self.buckets[bucket] if item["key"] != key] | |
self.buckets[bucket].remove(self.search(key)) | |
### Tests | |
myhashtable = hash_table(5) | |
print('### INSERT RESULTS ###') | |
myhashtable.insert('bono',25) | |
myhashtable.insert('mick',28) | |
myhashtable.insert('bruce',23) | |
myhashtable.insert('john',27) | |
myhashtable.insert('paul',24) | |
myhashtable.insert('ringo',28) | |
myhashtable.insert('george',27) | |
print(myhashtable) | |
print('### SEARCH RESULTS ###') | |
print(myhashtable.search('alec')) | |
print(myhashtable.search('paul')) | |
print('### DELETE RESULTS ###') | |
myhashtable.delete('ringo') | |
print(myhashtable) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment