Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search algorithm but for functions

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?

like image 953
Pwnna Avatar asked May 24 '12 13:05

Pwnna


People also ask

What are different types of search algorithm?

Search algorithms can be classified based on their mechanism of searching into three types of algorithms: linear, binary, and hashing.

What are the 2 types of searching algorithms?

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.

Which algorithm is best for searching?

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.

What is A heuristic function?

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.


1 Answers

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.

like image 144
Sven Marnach Avatar answered Sep 29 '22 02:09

Sven Marnach