0

I've noticed some recurring code in my project, involving finding the 'best match' to something in a list, with the important caveat that if there is a tie, the first is selected ie the order is important.

The project is in python, and the pattern looks like

things = <list of things>

highest_thing = None
highest_strength = 0

for thing in things:
    if thing.strength(some_params) > highest_strength:
        highest_thing = thing
        highest_strength = thing.strength(some_params)

I tried to do this with the built-in max function, using a dictionary comprehension to make a mapping from a thing to its strength, but the dictionary loses the order. I then found OrderedDict in Python, but feel this is importing more complexity than warrented, considering how simple the original solution is, despite looking very C-like.

Ideally, I want something like

highest_thing = highest(things, some_params)

without having to write this function myself (which is fine, but I can't help but think there's a nicer looking solution).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Gage
  • 303
  • 2
  • 6

1 Answers1

1

You do need to use the max() function but don't need to use a dictionary.

Use the key argument to calculate the highest_strength value by which max() should pick the highest thing:

highest_thing = max(things, key=lambda thing: thing.strength(some_params))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • is `max` guaranteed to return the first of the highest values? [this question](http://stackoverflow.com/questions/6783000/which-maximum-does-python-pick-in-the-case-of-a-tie) seems to suggest it's not well defined in the specification. `sort` however is stable, I could theoretically do it that way, but that's more convoluted. – Gage Mar 25 '15 at 19:02
  • @Gage: `max()`, like `sorted()` is stable in that it always picks a specific value given the same inputs. The implementation picks the first highest value in case of a tie; I guess it could also pick the last but there is no compelling reason to change that. – Martijn Pieters Mar 25 '15 at 19:16
  • @Gage: see [this post on Byte](http://bytes.com/topic/python/answers/536199-min-max-vs-sorted) for example; Tim Peters is the core Python developer that created the Tim Sort algorithm used in Python (and now in Java and other languages too). – Martijn Pieters Mar 25 '15 at 19:18
  • @Gage: if this matters to you across all Python variants, then you should either test all those variants or stick to your manual loop. – Martijn Pieters Mar 25 '15 at 19:22
  • Since my attempt broke my unit tests, I think I'll go for letting testing catch them. If the project ends up on a system that has a different implementation, it will clearly fail some tests. Thanks Martijn. – Gage Mar 25 '15 at 20:33