4
\$\begingroup\$

Getting started:

For a given number x (say -5) I want to know which element of a list y (say [2, -6]), minimizes the value of distance function d (say the absolute value) which applied on x and all elements of y. My current solution to this problem is

x = -5
y = [2, -6]
def d(a1, a2):
 return abs(a1-a2) # more complicated in real application
min(y, key = lambda _: d(_, x)) # correctly returns -6

Next level: x is actually a list (say [1, 5, -10]), so I build a list comprehension on top my previous solution:

x = [1, 5, -10]
[min(y, key = lambda _: d(_, xindex)) for xindex in x] # correctly returns [2, 2, -6]

As this type of problem seems quite basic to me, I expect a simple solution for this problem (like argmin(list1=x, list2=y, function=d)). Here is a question where it is shown how a custom distance matrix can be build. But this alone (the step from the distance matrix to the argmins would also have to be done) seems too be more complicated than my code.

Overall my question is: is my code fine, or is there a nicer solution?

AlexV
7,3532 gold badges24 silver badges47 bronze badges
asked Jul 1, 2019 at 13:10
\$\endgroup\$
2
  • \$\begingroup\$ Do you want to know the index of the value or the value itself that minimizes that distance? \$\endgroup\$ Commented Jul 1, 2019 at 13:25
  • 1
    \$\begingroup\$ @AlexV I want to know the value itself (eg [2, 2, -6]) that minimizes the distance. \$\endgroup\$ Commented Jul 1, 2019 at 13:30

1 Answer 1

3
\$\begingroup\$

The approach is fine and this is exactly the purpose of the key attribute of min.

I’d just nitpick that the _ variable name is usually meant to indicate unused arguments and thus, using it inside the lambda goes against conventions.

Alternatively, you can make use of functools.partial which may yield better performances on larger lists:

[min(y, key=partial(d, a2=xindex)) for xindex in x]
answered Jul 1, 2019 at 14:10
\$\endgroup\$
2
  • \$\begingroup\$ Thank your for your insights. Your solution only works if I add functools before partial ([min(y, key=functools.partial(d, a2=xindex)) for xindex in x]). Is this a special issue of my system (I'm using a jupyter notebook) or more general? \$\endgroup\$ Commented Jul 1, 2019 at 14:51
  • 3
    \$\begingroup\$ Have you tried from functools import partial? \$\endgroup\$ Commented Jul 1, 2019 at 18:00

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.