Kris
Kris

Reputation: 1556

Does exist built-in function in Python to find best value that satisfies some condition?

Does exist built-in function in Python, that can find best value that satisfies some condition (specified by a funciton)? For example something instead this code:

def argmin(seq, fn):
    best = seq[0]; best_score = fn(best)
    for x in seq:
        x_score = fn(x)
        if x_score < best_score:
            best, best_score = x, x_score
    return best

Upvotes: 2

Views: 604

Answers (3)

Slater Victoroff
Slater Victoroff

Reputation: 21914

If all you want is a strict optimization of one parameter, max and min work perfectly fine. That said, most interesting problems (in my opinion) rely on the optimization of at least two parameters at once according to some cost parameter. For any kind of non-linear optimization I would highly recommend scipy's optimize module. Documentation for that can be found here.

SLSQP is the most flexible optimization algorithm, so that may be helpful to you.

Upvotes: 0

hd1
hd1

Reputation: 34657

In general, you want the reduce function, but like @Lattyware said earlier, your specific example, max will suffice.

Upvotes: 1

Gareth Latty
Gareth Latty

Reputation: 88997

I presume by 'best' you mean highest, in which case the answer is simple - max().

It takes a key argument, which would be your function.

max(data, key=score)

Naturally, if 'best' means lowest, as DSM points out, then you just want min() instead, it does what it says on the tin.

Upvotes: 9

Related Questions