Break list comprehension

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

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

Now I want to interrupt the creation of the list if any of its elements is greater than B, and return this element. The result will be the same as:

 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, and creating smaller elements is slower than understanding the list of the problem I'm working on now. Is there a way to use list comprehension or the simillar generator method, but test it on B and abort the average iteration? The goal here is to ONLY calculate the NCESSARY elements, but run it faster than the first example (where it evaluates each element).

Edit: I tried many tips that you guys came up with and settled on a simple implementation of the while loop. The final code that I finished looks like this:

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

It works a little faster than for-loop, although there may be a faster solution (there is still no time for all the proposed solutions, sorry), but I like the simplicity.

Thanks.

+5
source share
2 answers

So, here is a generator that generates values ​​from its first argument until the value exceeds its second:

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

Then it works:

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

But it will not work as fast as a list comprehension.

+1
source

Try it like this:

 >>> [x**2 for x in range(10)] 

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

 [x**2 for x in range(10) if x < 7] 

[0, 1, 4, 9, 16, 25, 36]

EDIT: checked with [f (x) for x in the range (10) if f (x) 7] - and it calls the function f (x) twice, so it's even slower

-2
source

Source: https://habr.com/ru/post/1259509/


All Articles