views:

72

answers:

1

The problem:

I have a trie and I want to return the information stored in it. Some leaves have information (set as value > 0) and some leaves do not. I would like to return only those leaves that have a value.

As in all trie's number of leaves on each node is variable, and the key to each value is actually made up of the path necessary to reach each leaf.

I am trying to use a generator to traverse the tree postorder, but I cannot get it to work. What am I doing wrong?

My module:

class Node():
    '''Each leaf in the trie is a Node() class'''
    def __init__(self):
        self.children = {}
        self.value = 0

class Trie():
    '''The Trie() holds all nodes and can return a list of their values'''
    def __init__(self):
        self.root = Node()
    def add(self, key, value):
        '''Store a "value" in a position "key"'''
        node = self.root
        for digit in key:
            number = digit
            if number not in node.children:
                node.children[number] = Node()
            node = node.children[number]
        node.value = value
    def __iter__(self):
        return self.postorder(self.root)
    def postorder(self, node):
        if node:
            for child in node.children.values():
                self.postorder(child)
            # Do my printing / job related stuff here
            if node.value > 0:
                yield node.value

Example use:

>>trie = Trie()
>>trie.add('foo', 3)
>>trie.add('foobar', 5)
>>trie.add('fobaz', 23)

>>for key in trie:
>>....print key
>>
3
5
23

I know that the example given is simple and can be solved using any other data structure. However, it is important for this program to use a trie as it is very beneficial for the data access patterns.

Thanks for the help!

Note: I have omitted newlines in the code block to be able to copy-paste with greater ease.

+2  A: 

Change

self.postorder(child)

to

for n in self.postorder(child):
    yield n

seems to make it work.

P.S. It is very helpful for you to left out the blank lines for ease of cut & paste :)

Wai Yip Tung
+1. Perhaps add recursion to iterate over deeper descendants?
Tim McNamara