1

I would like to sort a list using a function that returns a float value. If the function had a single argument, I would simply use

sorted(mylist, key=myfunction)

and be on my merry way. However, this doesn't work for functions with multiple arguments. How can this be done?

This is a small part of a chess engine. The 'Bestmove' function takes in the board position (a list), the depth (an integer), and alpha/beta values and returns a list with two entries: the board evaluation (a float), and the suggested move (a list).

In an effort to optimize the alpha/beta pruning process, I would like to change the order in which moves are evaluated (strong moves evaluated first leads to greater efficiency). To achieve this, I would like to sort the list of moves by the first value in the list returned by the 'Bestmove' function.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
KingsGambit
  • 19
  • 1
  • 3
  • What do you anticipate the multiple arguments passed to this function actually being in this case? – miradulo Apr 20 '18 at 23:42
  • According to https://docs.python.org/3/howto/sorting.html#operator-module-functions if you use the itemgetter and attrgetter functions you can accomplish sorts of lists of tuples. What is your list composed of and what does your function sort on? – Kulix Apr 20 '18 at 23:48
  • 2
    `sorted(mylist, key=lambda x: myfunction(x, 42, 'foo'))`. – ekhumoro Apr 20 '18 at 23:51

1 Answers1

5

There are several ways you can do this. Assume we have a list lst.

Set default values

This works only if you can set in advance the default values for your unused parameters.

def func(x, y=1, z=2):
    return x + y + z

res = sorted(lst, key=func)

Use partial functions

You can use functools.partial to create a function with certain parameters fixed.

from functools import partial

def func(x, y, z):
    return x + y + z

res = sorted(lst, key=partial(func, y=1, z=2))

Pass through lambda

If your additional parameters are dependent on the list item itself, you can pass through an anonymous lambda and include your logic.

def func(x, y, z):
    return x + y + z

res = sorted(lst, key=lambda x: func(x, x+1, x+2))
jpp
  • 159,742
  • 34
  • 281
  • 339