0

I am currently trying to implement a trie datastructure in Python. The key difference is, instead of the canonical form of tracking only the children of each node, I am keeping track of each node's parents and a value (which I call index). I've delineated my line of confusion with **:

class Node:

    def __init__(self, c={}, p = None, i = None, is_leaf = False):
        self.children = c
        self.parent = p
        self.index = i
        self.is_leaf = is_leaf

class Trie:

    def __init__(self):
        self.root = self.get_node()
        self.last_added = 0

    def get_node(self):
        return Node()

    def add_node(self, key):

        current = self.root
        current.index = 0
        current.parent = Node(i = -1)

        for char in key:

            if char not in current.children:
                current.children[char] = Node(p = current, i = self.last_added +1)
                self.last_added += 1
            **current = current.children[char]

        current.is_leaf = True

My confusion is this: in my trie, I would like to point my current node to the next node current = current.children[char]. However, if I were to add the string 'ABACA' to my trie, I get the following output:

In: 
t = Trie()
t.add_node('ABACA')
t.root.children

Out:
{'A': <__main__.Node at 0x201ae4eb108>,
 'B': <__main__.Node at 0x201ae593948>,
 'C': <__main__.Node at 0x201ae593ac8>}

Somehow, I am not pointing my object current to the next node. Am I misunderstanding how the addresses of key, values are managed in Python? Sorry for such a naive question!

batlike
  • 668
  • 1
  • 7
  • 19
  • 1
    add a [`__str__`](https://docs.python.org/3/reference/datamodel.html?highlight=__str__#object.__str__) method to your `Node` class. [this](https://dbader.org/blog/python-repr-vs-str) may help. – hiro protagonist Feb 27 '20 at 06:07
  • Which Python implementation? There are many. – Peter Wood Feb 27 '20 at 06:10
  • I've posted my implementation above! @PeterWood – batlike Feb 27 '20 at 06:11
  • 1
    You shouldn’t use mutable data as default parameters. – Peter Wood Feb 27 '20 at 06:13
  • Sorry I misunderstood! This is in Python 3 – batlike Feb 27 '20 at 06:15
  • 2
    In `Node.__init__`, `c={}` is only evaluated once. Whenever `Node` is created with a default `c`, that same dict keeps getting added to nodes. Any node updating `c` updates that single dict for all. Instead default `c` to `None` and create dicts as needed: `if c is None: c = {}` – tdelaney Feb 27 '20 at 06:19
  • Wow thanks all! I'm learning a lot, thanks for being patient with me! These are all great resources – batlike Feb 27 '20 at 06:22
  • 1
    I put the fix in and your code worked, so I'll mark this as a dup of @metatoaster's link. – tdelaney Feb 27 '20 at 06:34

0 Answers0