Home > Back-end >  Function writing to the same dictionary or just not writing in it at all
Function writing to the same dictionary or just not writing in it at all

Time:02-15

I am working on an Huffman project and I have an issue with one specific function. Basically where you create the dictionary from the tree to get the new dict with letters as keys and Huffman code as value (0 and 1).

Btw the whole program is actually way longer obviously but to make it easy for you I just put the non working function as the rest is working as intended.

And the « error » is that when I call my function multiple times it will just write to the same dictionary and replace some keys if they are the same. I tried putting codes = {} in the function itself or as args but then it would return an empty dictionary.

Here is the code :

codes = {}
def parcours(arbre, chemin=""):
    
    if arbre.gauche is None:
        codes[arbre.valeur] = chemin
    else:
        parcours(arbre.gauche, chemin "0")
        parcours(arbre.droit, chemin "1")
    return codes
        
    
    
print(parcours(creer_arbre(creer_liste(dict_exemple))))
print(parcours(arbre_huffman("testpy.txt")))

Here is what it returns :

{'b': '00', 'a': '01', 'd': '100', 'e': '1010', 'f': '1011', 'c': '11'}
{'b': '00', 'a': '01', 'd': '100', 'e': '101', 'f': '1011', 'c': '11', ' ': '000', 'p': '001', 'r': '010', 'o': '011', 'j': '100', 't': '110', 'T': '1110', 's': '1111'}

Letters are just from an example dictionary but the result clearly shows that the beginning of second run is the same as first run.

Sorry if it’s in French but it should be easy to understand, chemin is « path ». Parcours is like to navigate the tree, arbre is tree, valeur is value.

CodePudding user response:

If you define codes outside the function, every function call is adding its data to the same dict.

You need to define codes inside the function, and make sure to update it with the result of the recursive calls.

def parcours(arbre, chemin=""):
    codes = {}
    if arbre.gauche is None:
        codes[arbre.valeur] = chemin
    else:
        codes.update(parcours(arbre.gauche, chemin "0"))
        codes.update(parcours(arbre.droit, chemin "1"))
    return codes
  • Related