Build a Hash Table, remove() does not work

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 :sweat_smile: 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'))

You are doing good with our print() statements, it looks like you are doing good work with debugging.

You are missing something tho, you will see it if you try with this example

ht = HashTable()
ht.add('fcc', 'coding')
print(ht.hash('fcc'), ht.hash('cfc'))
print(ht.collection)
ht.remove('cfc')
print(ht.collection)

cfc was never part of the table, right? so what should happen with this? what happens instead?


For F12, that is the browser console, but this is a Python project, there are some things that are outputted to the console when you run the tests, but for Python you need to rely on the terminal

Yes, I saw that both dictionaries with ‘cfc’ or ‘fcc’ are deleted because they have the same hash value. :folded_hands:

I tried to solve the problem. This code passes:

"""
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)))
        # type of self.collection.keys() is dict_keys
        print("self.collection.keys()=", self.collection.keys())

        key2 = (self.hash(key))
        if key2 in list(self.collection.keys()):
            if self.lookup(key): # if the key itself exist, not only its hash (which, may be same for different keys).
                print("key exists in self.collection.keys():", key2)
                
                existing_value = self.collection.get(key2)
                print("existing_value before removal=",self.collection.get(key2))
                print("about to remove.")
                existing_value.pop(key)
                print("existing_value after removal=",self.collection.get(key2))

        else:
            
            print("key not found:", key)
        return

    def lookup(self, key):  # This function is really helpful when removing an item. instead of writing and thinking a lot, just call this.
        k_int = (self.hash(key))
        if k_int in list(self.collection.keys()):
            print('\nIn lookup(): key, self.collection.get(k_int)=', 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')

# Test.11
print("\n ht.collection before remove() =\n", ht.collection)
ht.remove('cfc')
print("\n ht.collection after remove() =\n", ht.collection)

# ###############################################################
# # @ILM help: You are missing something tho, you will see it if you try with this example
# ht = HashTable()
# ht.add('fcc', 'coding')
# print("ht.hash('fcc'), ht.hash('cfc')= ",ht.hash('fcc'), ht.hash('cfc'))
# print("ht.collection before remove=",ht.collection)
# ht.remove('cfc')
# print("\n ht.collection=\n", ht.collection)
# ####### result: if you add sth with 'fcc' key, it will be deleted later with anything that has the same hash, e.g.: 'cfc' (meaning of Test 10)
# ##########################################################


# 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'))

with this output:


 ht.collection before remove() =
 {424: {'golf': 'sport'}, 300: {'fcc': 'coding', 'cfc': 'chemical'}}

 In remove, self.hash(key)= 300
self.collection.keys()= dict_keys([424, 300])

In lookup(): key, self.collection.get(k_int)= cfc , {'fcc': 'coding', 'cfc': 'chemical'}
key exists in self.collection.keys(): 300
existing_value before removal= {'fcc': 'coding', 'cfc': 'chemical'}
about to remove.
existing_value after removal= {'fcc': 'coding'}

 ht.collection after remove() =
 {424: {'golf': 'sport'}, 300: {'fcc': 'coding'}}

: anger_symbol:But I am in a great confusion why it can pass.
Let’s look at the code in remove() , this time without print() statements to see it better:

    def remove(self, key):
        key2 = (self.hash(key))
        if key2 in list(self.collection.keys()):
            if self.lookup(key):                             
                existing_value = self.collection.get(key2)
                existing_value.pop(key)              
        else:
            print("key not found:", key)
        return

The line existing_value.pop(key) causes my ht Object to change. So, the test passes. I did not expect this because existing_value variable is considered to be a local temporary variable. Not something like a "Change it By reference (As I learned in QBasic)/ or sth like a pointer in C which changing it changes the exact object. I mean existing_value = self.collection.get(key2) was expected to have a copy of a dictionary in it.
Please explain.

when you use lists or dictionaries, there is an effect called “Passed by reference”

when you do existing_value = self.collection.get(key2), you are getting a reference to the same thing that exists inside the collection, that means that you are working on the same object, you would need to create a copy to avoid changing the same object

and you only create a copy if you explicitly do it

like, it’s the same effect as

a = {'greeting': 'hello'}
b = a
b['greeting'] = 'hi'
print(a) # {'greeting': 'hi'} (changed, because b and a are the same)
c = a.copy()
c['greeting'] = 'howdy'
print(a) # {'greeting': 'hi'} (not changed, c is a copy)

Did not expect that at all. Thanks.
With your explanation I conclude there is no exact way to set if a variable is sent “By val” or “By Ref”. You just should know that out of your negative experiences? This is not what expected from python. It has come to solve ancient problems, not to add to them :face_with_hand_over_mouth:

yeah, immutable things (strings, numbers, etc) are passed by value, everything else is passed by reference

This was a great explanation.