Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use <a href="http://docs.python.org/tutorial/classes.html#generators" rel="nofollow">generators</a>, which are just iterators written as functions that yield results. In this case you can write generators for <code>iter1</code> and <code>iter2</code> and another generator to wrap them and yield their results (or do calculations with them, or the history of their results) as you go.</p> <p>From my reading of the question you want something like this, which will <em>calculate every element of the first iterator with every element of the next, using said operation</em>, you also state you want some way to <em>wrap-up "iter1", "iter2", and "op" in an iterable that itself yields the values in monotonically increasing output</em>. I propose generators offer a simple solution to such problem.</p> <pre><code>import itertools def prime_gen(): D, q = {}, 2 while True: if q not in D: yield q D[q * q] = [q] else: for p in D[q]: D.setdefault(p + q, []).append(p) del D[q] q += 1 def infinite_gen(op, iter1, iter2): while True: yield op(iter1.next(), iter2.next()) &gt;&gt;&gt; gen = infinite_gen(operator.mul, prime_gen(), itertools.count()) &gt;&gt;&gt; gen.next() &lt;&lt;&lt; 0 &gt;&gt;&gt; gen.next() &lt;&lt;&lt; 3 &gt;&gt;&gt; gen.next() &lt;&lt;&lt; 10 </code></pre> <p>Generators offer a lot of flexibility, so it should be fairly easy to write <code>iter1</code> and <code>iter2</code> as generators that return values you want in the order you want. You could also consider using <a href="http://www.python.org/dev/peps/pep-0342/" rel="nofollow">coroutines</a>, which let you send values <em>into</em> a generator. </p>
 

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