In this Lab, called “Build a Hash Table”, I cannot pass Test 10. (Later I want to work on Test 11)
I have read this topic in forum that was the nearest topic related to my problem. However, I am still unable to continue.
When I test my code it seems okay and the console gives me no hint about where the problem is.
Q1) Is it possible to use F12 here? how? I opened Console tab in Firefox under Win 10 and could not find relevant thing.
Q2) Is there any other way I can understand its meaning? It is important to me because I want to be able to find my errors and situations better, not to pass with a remedy.
Q3) my code seems strange to myself
For example, how do you recommend to write ‘add()’ or ‘remove()’ ? Any other suggestions is appreciated.
Q4) Is it okay that I pasted the full code here?
Full code:
"""
Lab
https://www.freecodecamp.org/learn/python-v9/lab-hash-table/build-a-hash-table
"""
class HashTable():
def __init__(self):
self.collection=dict()
def hash(self,str1):
hashed_value=0
for char in str1:
hashed_value+= ord(char)
#print('\n',char,' ',hashed_value )
return hashed_value
def add(self,key,value):
k_int=(self.hash(key)) # k should be int
#print('in add(): k_int, key, value =',k_int,',',key,',',value)
value_to_add={key:value}
if k_int in self.collection:
existing_value= self.collection.get(k_int)
existing_value.update(value_to_add)
else:
self.collection.update({k_int:value_to_add})
def remove(self, key):
#print("removing, self.hash(key)= ","'"+str(self.hash(key))+"'")
print("\n In remove, self.hash(key)=", str(self.hash(key)))
print("self.collection.keys()=",self.collection.keys())# type of self.collection.keys() is dict_keys
key2= (self.hash(key))
if key2 in list(self.collection.keys()):
print("key exists in self.collection.keys():", key2)
self.collection.pop(key2)
else:
pass
#print("key not found:", key2)
return
def lookup(self,key):
k_int=(self.hash(key))
if k_int in list(self.collection.keys()):
print('\nIn lookup():',key,self.collection.get(k_int) )
desired_dict = self.collection.get(k_int)
return desired_dict.get(key)
else:
print('\nIn lookup(): key not found')
return None
ht= HashTable()
#print(ht.hash('golf'))
ht.add('golf', 'sport')
# ht.add('soccer', 'sport2')
# ht.add('ragby', 'sport3')
# ht.add('rose', 'flower')
# print('\n Guide Test 16:\n') #should add both the key-value pairs to the collection at index 412 as a nested dictionary.
# ht.add('dear', 'friend')
# ht.add('read', 'book')
#print('\n Guide Test 22:\n') #{ 300: { 'fcc': 'coding', 'cfc': 'chemical' }}
ht.add('fcc', 'coding')
ht.add('cfc', 'chemical')
print("\n ht.collection before remove() =\n",ht.collection)
ht.remove('unavailable') #Guide Test 10: when removing a key that does not exist...
print("\n ht.collection=\n",ht.collection)
# for key,v in ht.collection.items():
# print('k,v=',key,',', v)
# print("\nkeys in this collection:")
# for key in ht.collection.keys():
# print (key)
#print("\n result of calling: ht.lookup('golf'):\n",ht.lookup('golf'))