Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abort a list comprehension

I have a function in python2.7.12 that generates a list from a function f(x) and takes the maximum value like this:

max( [f(x) for x in range(n)] )

Now I want to abort the generation of the list in case any of its elements is greater than B, and return that element. The result would be the same as doing:

v = -float("inf")
for x in range(n):
    v = max( v, f(x) )
    if v > B: return v
return v

the problem is the for-loop, while generating less elements, runs slower than the list comprehension for the problem I'm currently working on. Is there a way to use list comprehension or a simillar generator method, but have it check against B and abort mid-iteration? The objective here is to calculate ONLY the NCESSARY elements, but have it run faster than the first example (where it calculates every element).

Edit: I have tried many of the tips you guys came up with and settled for the simple implementation of a while-loop. The final code I ended up with is as follows:

v = float("-inf")
x = 0
while x < n:
    v = max( v, f(x) )
    if v > B: return v

It runs somewhat faster than the for-loop, even though there may be a faster solution (still didn't time all of the proposed solutions, sorry), but I like the simplicity.

Thank you.

like image 222
Kevin Liu Avatar asked Nov 27 '22 03:11

Kevin Liu


1 Answers

So here is a generator that generates values from its first argument until a value is over its second:

def generate_until_threshold(iterator, threshold):
    for value in iterator:
        yield value
        if value > threshold:
            return

Then this works:

max(generate_until_threshold((f(x) for x in range(n)), B), -float('inf'))

But it will not run as fast as the list comprehension.

like image 144
RemcoGerlich Avatar answered Nov 28 '22 17:11

RemcoGerlich