10
\$\begingroup\$

I have a list, l and a function f. f is not strictly increasing or decreasing. How can I find the item in the list whose f(item) is the smallest? For example, let's say the list is:

l = [1, 2, 3, 4]

and list(f(x)for x in l) is:

[2, 9, 0, 3]

f(3) is smaller than f of any of the other ones, so it should print "3". What's the shortest way to do this? I initially tried:

min(f(x) for x in l)

But this gives 0, not 3. If I was shooting for readability, not brevity, I would do:

index = 0
smallest = f(l[0])
for i in range(len(l)):
    value = f(l[i])
    if value < smallest:
        smallest = value
        index = i

This is fine, but horrendous for code-golf. Even if it was golfed

i,s=0,f(l[0])
for x in range(len(l)):
 v=f(l[x])
 if v<s:s,i=v,x

This is a bad solution. The shortest solution I can think of is:

g=[f(x)for x in l];print(l[g.index(min(g))])

(44 bytes) How can I golf this down further?

\$\endgroup\$
  • 8
    \$\begingroup\$ Just min(l,key=f). \$\endgroup\$ – vaultah May 17 '16 at 19:42
  • 2
    \$\begingroup\$ @vaultah Post that as an answer. \$\endgroup\$ – NoOneIsHere May 17 '16 at 19:46
  • 4
    \$\begingroup\$ @KevinLau-notKenny This is a tips question. That is on-topic. \$\endgroup\$ – NoOneIsHere May 17 '16 at 19:50
  • 2
    \$\begingroup\$ @trichoplax actually I think it's this one: meta.codegolf.stackexchange.com/a/1724/31625 \$\endgroup\$ – FryAmTheEggman May 17 '16 at 19:51
  • 2
    \$\begingroup\$ This is an interesting topic. Perhaps make it general, not limited to Python? It may be interesting to see how to do that in different languages \$\endgroup\$ – Luis Mendo May 17 '16 at 20:29
10
\$\begingroup\$

Use key property of min

As @vaultah said, use min(l,key=f). min(l,key=f) takes the minimum of f(i) for i in l.

It is also possible to apply this to max, and sorted. For example, max(l,key=f) is the maximum of f(i) for i in l. For sorted, the usage would be: sorted(l,key=f).

\$\endgroup\$
  • 1
    \$\begingroup\$ I'm accepting this for now, but will accept an answer from @vaultah if he posts it. \$\endgroup\$ – DJMcMayhem May 18 '16 at 23:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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