Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Warning</strong> This is a bit convoluted but does the job. I will use an example to explain it.</p> <p>Let say <code>expensive_function = math.sin</code></p> <p><code>infinite generator = collections.count(0.1,0.1)</code></p> <p>then </p> <pre><code>[z for z in (y if y &lt; 5 else next(iter([])) for y in (math.sin(x) for x in itertools.count(0.1,0.1)))] </code></pre> <p>is</p> <pre><code>[0.09983341664682815, 0.19866933079506122, 0.2955202066613396, 0.3894183423086505, 0.479425538604203] </code></pre> <p>So your problem boils down to</p> <pre><code>[z for z in (y if y &lt; 0.5 else next(iter([])) \ for y in (expensive_function(x) for x in generator))] </code></pre> <p>The trick is to force a <code>StopIteration</code> from a generator and nothing elegant than <code>next(iter([]))</code></p> <p>Here <code>expensive_function</code> is only called once per iteration.</p> <p>Extend the Infinite Generator with a Finite Generator, with the Stop Condition. As the generator won't allow <code>raise StopIteration</code>, we opt for a convoluted way i.e. <code>next(iter([]))</code> And now you have a Finite Generator, which can be used in a List Comprehension</p> <p>As OP was concerned with the application of the above method for a non-<a href="http://en.wikipedia.org/wiki/Monotonic_function" rel="nofollow">monotonic</a> function here is a fictitious non-monotonic function</p> <p>Expensive Non-Monotonic Function <code>f(x) = random.randint(1,100)*x</code></p> <p>Stop Condition = <code>&lt; 7</code></p> <pre><code>[z for z in (y if y &lt; 7 else next(iter([])) for y in (random.randint(1,10)*x for x in itertools.count(0.1,0.1)))] [0.9, 0.6000000000000001, 1.8000000000000003, 4.0, 0.5, 6.0, 4.8999999999999995, 3.1999999999999997, 3.5999999999999996, 5.999999999999999] </code></pre> <p>Btw: <code>sin</code> in true sense is non-monotonic over the entire range <code>(0,2pi)</code></p>
    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. 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