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?

\$\endgroup\$
2
  • \$\begingroup\$ Do you want to know the index of the value or the value itself that minimizes that distance? \$\endgroup\$
    – AlexV
    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\$
    – Qaswed
    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]
\$\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\$
    – Qaswed
    Jul 1, 2019 at 14:51
  • 3
    \$\begingroup\$ Have you tried from functools import partial? \$\endgroup\$
    – TCFP
    Jul 1, 2019 at 18:00

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.