implementing argmax in Python

后端 未结 5 2267
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 14:51

How should argmax be implemented in Python? It should be as efficient as possible, so it should work with iterables.

Three ways it could be implemented:

    <
5条回答
  •  余生分开走
    2020-12-08 15:47

    I found this way easier to think about argmax: say we want to calculate argmax(f(y)) where y is an item from Y. So for each y we want to calculate f(y) and get y with maximum f(y).

    This definition of argmax is general, unlike "given an iterable of values return the index of the greatest value" (and it is also quite natural IMHO).

    And ..drumroll.. Python allows to do exactly this using a built-in max:

    best_y = max(Y, key=f)
    

    So argmax_f (from the accepted answer) is unnecesary complicated and inefficient IMHO - it is a complicated version of built-in max. All other argmax-like tasks should become clear at this point: just define a proper function f.

提交回复
热议问题