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.
source share