Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It sounds like you want the iterator to act as a tree traversal. Study the <code>itertools</code> module and you can really go places.</p> <pre><code>from itertools import chain, imap class t: def __init__(self, value): self.value = value self.children = [] def __iter__(self): "implement the iterator protocol" for v in chain(*imap(iter, self.children)): yield v yield self.value root = t(0) root.children.append(t(1)) root.children.append(t(2)) root.children[1].children.append(t(3)) print list(iter(root)) # -&gt; [1, 3, 2, 0] print list(iter(root.children[1])) # -&gt; [3, 2] </code></pre> <p><strong>EDIT</strong>: Below is the originally accepted implementation. It has a performance problem; I would remove it, but it seems wrong to remove content that was an accepted answer. It will fully traverse the entire structure, creating <code>O(N*log[M](N))</code> generator objects (for a balanced tree with branching factor <code>M</code> containing <code>N</code> total elements), before yielding any values. But it does produce the desired result with a simple expression.</p> <p>(The above implementation visits areas of the tree on demand and has only <code>O(M+log[M](N))</code> generator objects in memory at a time. In both implementations, only <code>O(log[M](N))</code> levels of nested generators are expected.)</p> <pre><code>from itertools import chain def isingle(item): "iterator that yields only a single value then stops, for chaining" yield item class t: # copy __init__ from above def __iter__(self): "implement the iterator protocol" return chain(*(map(iter, self.children) + [isingle(self.value)])) </code></pre>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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