Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are several issues you're running into. The first is that if you have several children at the same level, you'll only be prefixing one of them with the initial part of the string, and just showing the suffix of the others. Another issue is that you're only showing leaf nodes, even though you can have terminal values that are not at a leaf (consider what happens when you use both <code>"foo"</code> and <code>"foobar"</code> as keys into a Trie). Finally, you're not outputting the values at all.</p> <p>To solve the first issue, I suggest using a recursive generator that does the traversal of the Trie. Separating the traversal from <code>__str__</code> makes things easier since the generator can simply <code>yield</code> each value we come across, rather than needing to build up a string as we go. The <code>__str__</code> method can assemble the final result easily using <code>str.join</code>.</p> <p>For the second issue, you should yield the current node's key and value whenever <code>self.val</code> is not <code>None</code>, rather than only at leaf nodes. As long as you don't have any way to remove values, all leaf nodes will have a value, but we don't actually need any special casing to detect that.</p> <p>And for the final issue, I suggest using string formatting to make a <code>key:value</code> pair. (I suppose you can skip this if you really don't need the values.)</p> <p>Here's some code:</p> <pre><code>def traverse(self, prefix=""): if self.val is not None: yield "{}:{}".format(prefix, self.val) for letter, child in self.children.items(): yield from child.traverse(prefix + letter) def __str__(self): return " | ".join(self.traverse()) </code></pre> <p>If you're using a version of Python before 3.3, you'll need to replace the <code>yield from</code> statement with an explicit loop to yield the items from the recursive calls:</p> <pre><code>for item in child.traverse(prefix + letter) yield item </code></pre> <p>Example output:</p> <pre><code>&gt;&gt;&gt; t = Trie() &gt;&gt;&gt; t.insert("foo", 5) &gt;&gt;&gt; t.insert("bar", 10) &gt;&gt;&gt; t.insert("foobar", 100) &gt;&gt;&gt; str(t) 'bar:10 | foo:5 | foobar:100' </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload