Given a list of input (let's say they are just integers), and a list of functions (and these functions takes an integer, and returns either True or False).
I have to take this list of input, and see if any function in the list would return True for any value in the list.
Is there any way to do this faster than O(n^2)
Right now what I have is
for v in values:
for f in functions:
if f(v):
# do something to v
break
Any faster methods?
Search algorithms can be classified based on their mechanism of searching into three types of algorithms: linear, binary, and hashing.
In searching, there are two types: sequential search and interval search. Almost every search algorithm falls into one of these two categories. Linear and binary searches are two simple and easy-to-implement algorithms, with binary algorithms performing faster than linear algorithms.
The binary search algorithm works on the principle of divide and conquer and it is considered the best searching algorithm because it's faster to run.
A heuristic function, also simply called a heuristic, is a function that ranks different in search algorithms at each branching step based on available information to decide which branch to follow. For example, it may approximate the exact solution.
Without any further information on the functions, the results of the len(functions) * len(values)
possible function calls must be considered independent from each other, so there is no faster way than checking them all.
You can write this a little more concisely, though:
any(f(v) for v in values for f in functions)
The builtin function any()
also short-circuits, just like your original code.
Edit: It turns out that the desired equivalent would have been
all(any(f(v) for f in functions) for v in values)
See the comments for a discussion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With