Skip to content

Instantly share code, notes, and snippets.

@gunnarig
Created November 16, 2019 21:54
Show Gist options
  • Save gunnarig/4e448922150d98ac140dc46eca20a80d to your computer and use it in GitHub Desktop.
Save gunnarig/4e448922150d98ac140dc46eca20a80d to your computer and use it in GitHub Desktop.
class NotFoundException(Exception):
pass
class Bucket:
def __init__(self):
self.bucket = []
self.size = 0
def __str__(self):
if len(self.bucket) == 0:
return None
else:
loadstring = ""
string = ""
for items in self.bucket:
string = str(items)
loadstring = loadstring + string
return loadstring
class HashMap:
def __init__(self):
self.size = 16
self.arr = [None]*self.size
self.items = 0
def __hash__(self,key):
key = (key^2)+997
newkey = (key) % self.size
return newkey
def __setitem__(self, key, data):
target_key = self.__hash__(key)
if self.arr[target_key] == None:
new_bucket = Bucket()
new_bucket.bucket.append([key,data])
new_bucket.size += 1
self.arr[target_key] = new_bucket
elif self.arr[target_key].size >= 1:
for i in range(0,self.arr[target_key].size-1):
print(self.arr[target_key].bucket[i])
print(self.arr[target_key].bucket[i][0])
if self.arr[target_key].bucket[i][0] == key:
self.arr[target_key].bucket[i][1] = data
return
self.arr[target_key].bucket.append([key,data])
self.arr[target_key].size += 1
def __getitem__(self, key):
target_key = self.__hash__(key)
if self.arr[target_key] == None:
raise NotFoundException
elif self.arr[target_key].size >= 1:
for i in range(0,self.arr[target_key].size):
print(self.arr[target_key].bucket[i][0])
if self.arr[target_key].bucket[i][0] == key:
return self.arr[target_key].bucket[i][1]
else:
pass
raise NotFoundException
def __len__(self):
pass
if __name__ == "__main__":
print("\nTESTING HASHMAP - MAKE BETTER TESTS!!")
m = HashMap()
m[3] = "Value for key: 3"
m[6] = "Value for key: 6"
m[2] = "Value for key: 2"
m[2] = "Value for key: 2 new and improved"
m[5] = "Value for key: 5"
m[7] = "Value for key: 7"
m[10] = "Value for key: 10"
m[11] = "Value for key: 11"
m[15] = "Value for key: 15"
m[16] = "Value for key: 16"
m[17] = "Value for key: 17"
m[19] = "Value for key: 19"
m[20] = "Value for key: 20"
m[32] = "Value for key: 32"
m[23] = "Value for key: 23"
m[24] = "Value for key: 24"
m[26] = "Value for key: 26"
m[29] = "Value for key: 29"
m[50] = "Value for key: 50"
m[49] = "Value for key: 49"
m[38] = "Value for key: 38"
m[44] = "Value for key: 44"
m[42] = "Value for key: 42"
print("")
try:
print(str(m[2]))
except(NotFoundException):
print("Item not found")
try:
print(str(m[3]))
except(NotFoundException):
print("Item not found")
try:
print(str(m[4]))
except(NotFoundException):
print("Item not found")
try:
print(str(m[5]))
except(NotFoundException):
print("Item not found")
try:
print(str(m[6]))
except(NotFoundException):
print("Item not found")
# print("Size of collection: " + str(len(m)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment