Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #9957

Re: Pythonic way with more than one max possible

Date 2011-07-20 12:51 +0200
From Thomas Jollans <t@jollybox.de>
Subject Re: Pythonic way with more than one max possible
References <acfc6e53-fd3c-4404-9314-aa01dc35c0d7@a31g2000vbt.googlegroups.com> <4e265748$0$29970$c3e8da3$5496439d@news.astraweb.com>
Newsgroups comp.lang.python
Message-ID <mailman.1287.1311159102.1164.python-list@python.org> (permalink)

Show all headers | View raw


On 20/07/11 06:19, Steven D'Aprano wrote:
> On Wed, 20 Jul 2011 01:17 pm CM wrote:
> 
>> I have three items in a dict, like this:
>>
>> the_dict = {'a':1, 'b':2, 'c':3}
>>
>> but the vals could be anything.  I want to configure something else
>> based on the "winner" of such a dict, with these rules:
>>
>> 1. In this dict, if there is a UNIQUE max value, that's the winner.
>> 2. If there are any TIES for max value, b is the winner by default.
>>
>> The problem for me, as I see it, is I don't know any elegant ways to
>> do this in Python.  The max(dict) function doesn't distinguish between
>> unique and non-unique maxes.  I could go through and test the various
>> possibilities (to see if the max value had any matches in the other
>> values), but, knowing Python, there is probably something close to
>> "one way to do it".  Any suggestions?
> 
> # Untested.
> def get_winner(adict):
>     values = sorted(adict.values(), reverse=True)
>     if values[0] == values[1]:
>         return adict['b']
>     else:
>         return values[0]

# Untested, with keys:
def get_winner(adict):
    values = sorted(adict.items(), reverse=True,
                    key=(lambda k_v: k_v[1]))
    if values[0][1] == values[1][1]:
        return 'b'
    else:
        return values[0][0]

> 
> Assumes that adict has at least two items. May be slow if it has millions of
> items.
> 
> 

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Pythonic way with more than one max possible CM <cmpython@gmail.com> - 2011-07-19 20:17 -0700
  Re: Pythonic way with more than one max possible Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-20 14:19 +1000
    Re: Pythonic way with more than one max possible Thomas Jollans <t@jollybox.de> - 2011-07-20 12:51 +0200
  Re: Pythonic way with more than one max possible Chris Rebert <clp2@rebertia.com> - 2011-07-19 21:33 -0700
  Re: Pythonic way with more than one max possible CM <cmpython@gmail.com> - 2011-07-19 22:10 -0700
    Re: Pythonic way with more than one max possible woooee <woooee@gmail.com> - 2011-07-19 22:37 -0700
    Re: Pythonic way with more than one max possible Chris Rebert <clp2@rebertia.com> - 2011-07-19 23:56 -0700
  Re: Pythonic way with more than one max possible CM <cmpython@gmail.com> - 2011-07-20 13:25 -0700

csiph-web