Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I had used something similar in order to build somithing similar <a href="http://en.wikipedia.org/wiki/Trie" rel="nofollow">Trie</a> for an application. I hope it helps.</p> <pre><code>class Trie: """ A Trie is like a dictionary in that it maps keys to values. However, because of the way keys are stored, it allows look up based on the longest prefix that matches. """ def __init__(self): # Every node consists of a list with two position. In # the first one,there is the value while on the second # one a dictionary which leads to the rest of the nodes. self.root = [0, {}] def insert(self, key): """ Add the given value for the given key. &gt;&gt;&gt; a = Trie() &gt;&gt;&gt; a.insert('kalo') &gt;&gt;&gt; print(a) [0, {'k': [1, {'a': [1, {'l': [1, {'o': [1, {}]}]}]}]}] &gt;&gt;&gt; a.insert('kalo') &gt;&gt;&gt; print(a) [0, {'k': [2, {'a': [2, {'l': [2, {'o': [2, {}]}]}]}]}] &gt;&gt;&gt; b = Trie() &gt;&gt;&gt; b.insert('heh') &gt;&gt;&gt; b.insert('ha') &gt;&gt;&gt; print(b) [0, {'h': [2, {'a': [1, {}], 'e': [1, {'h': [1, {}]}]}]}] """ # find the node to append the new value. curr_node = self.root for k in key: curr_node = curr_node[1].setdefault(k, [0, {}]) curr_node[0] += 1 def find(self, key): """ Return the value for the given key or None if key not found. &gt;&gt;&gt; a = Trie() &gt;&gt;&gt; a.insert('ha') &gt;&gt;&gt; a.insert('ha') &gt;&gt;&gt; a.insert('he') &gt;&gt;&gt; a.insert('ho') &gt;&gt;&gt; print(a.find('h')) 4 &gt;&gt;&gt; print(a.find('ha')) 2 &gt;&gt;&gt; print(a.find('he')) 1 """ curr_node = self.root for k in key: try: curr_node = curr_node[1][k] except KeyError: return 0 return curr_node[0] def __str__(self): return str(self.root) def __getitem__(self, key): curr_node = self.root for k in key: try: curr_node = curr_node[1][k] except KeyError: yield None for k in curr_node[1]: yield k, curr_node[1][k][0] if __name__ == '__main__': a = Trie() a.insert('kalo') a.insert('kala') a.insert('kal') a.insert('kata') print(a.find('kala')) for b in a['ka']: print(b) print(a) </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.
    2. VO
      singulars
      1. This table or related slice is empty.
    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