mercredi 25 mars 2015

Pattern for finding maximum match in ordered-important list

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


Aucun commentaire:

Enregistrer un commentaire