Search code examples
pythonalgorithmdata-structuresimplementationtrie

Python Trie implementation why create temporary variable


I looked at this code:

>>> _end = '_end_'
>>> 
>>> def make_trie(*words):
...     root = dict()
...     for word in words:
...         current_dict = root
...         for letter in word:
...             current_dict = current_dict.setdefault(letter, {})
...         current_dict = current_dict.setdefault(_end, _end)
...     return root
... 
>>> make_trie('foo', 'bar', 'baz', 'barz')
{'b': {'a': {'r': {'_end_': '_end_', 'z': {'_end_': '_end_'}}, 
         'z': {'_end_': '_end_'}}}, 
'f': {'o': {'o': {'_end_': '_end_'}}}}

from this link: How to create a TRIE in Python, but I don't quite understand why does the author create the temporary variable current_dict since you are always just editing the dictionary called root...


Solution

  • I don't quite understand why does the author create the temporary variable current_dict since you are always just editing the dictionary called root...

    No, you're not. If it was always editing the root dictionary, the result would be very different. Every time the assignment inside the loop is executed:

    ...         current_dict = root
    ...         for letter in word:
    ...             current_dict = current_dict.setdefault(letter, {}) # this one
    

    current_dict is set to a dictionary one level further in. This loop traverses the trie, using setdefault to build missing parts as needed. We have to assign the setdefault result to current_dict to keep going down the trie instead of staying at top level, and we have to use a separate current_dict variable instead of root so we can assign current_dict = root to get back to top level once we're done with a word.