How to find the item in a list whose f(item) is the smallest?

10

1

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?

James

Posted 2016-05-17T19:41:20.440

Reputation: 54 537

8Just min(l,key=f). – vaultah – 2016-05-17T19:42:16.587

2@vaultah Post that as an answer. – NoOneIsHere – 2016-05-17T19:46:51.847

@vaultah Wow. That is embarrassingly simple. I feel like an idiot now. Thanks! If you post that, I'd accept it. – James – 2016-05-17T19:47:54.093

This kind of question isn't for code golf, but for stackoverflow or some other subsection of stackexchange. Voting to close as off-topic – Value Ink – 2016-05-17T19:50:00.913

4@KevinLau-notKenny This is a [tag:tips] question. That is on-topic. – NoOneIsHere – 2016-05-17T19:50:47.350

2

@trichoplax actually I think it's this one: http://meta.codegolf.stackexchange.com/a/1724/31625

– FryAmTheEggman – 2016-05-17T19:51:58.177

@FryAmTheEggman you're right - I just reread the title... Thanks :) – trichoplax – 2016-05-17T19:55:53.297

@DrGreenEggsandHamDJ the fact that an elegant solution comes along doesn't change that it's a good question... – trichoplax – 2016-05-17T19:58:46.283

Does the answer have to be in Python? – Adám – 2016-05-17T20:08:56.063

@Nᴮᶻ In general for code-golf, no. However, this isn't a code-golf question, but a [tag:tips] question (about code-golf). – James – 2016-05-17T20:09:59.367

@DrGreenEggsandHamDJ Still doesn't hurt, does it? ;-) – Adám – 2016-05-17T20:15:13.560

2This 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 – Luis Mendo – 2016-05-17T20:29:13.797

Answers

10

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).

NoOneIsHere

Posted 2016-05-17T19:41:20.440

Reputation: 1 916

1I'm accepting this for now, but will accept an answer from @vaultah if he posts it. – James – 2016-05-18T23:03:07.987