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


Groups > comp.lang.python > #76598

Re: More Pythonic implementation

References <CAGOccLmG3UzUtn3+Dy1ADDvGD3P14GZp0V5s4_x-_9HRJeY2XA@mail.gmail.com>
From Chris Kaynor <ckaynor@zindagigames.com>
Date 2014-08-19 11:57 -0700
Subject Re: More Pythonic implementation
Newsgroups comp.lang.python
Message-ID <mailman.13163.1408474700.18130.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

On Tue, Aug 19, 2014 at 10:09 AM, Shubham Tomar <tomarshubham24@gmail.com>
wrote:

> Lets say I have a function poker(hands) that takes a list of hands and
> returns the highest ranking hand, and another function hand_rank(hand) that
> takes hand and return its rank. As in Poker
> http://www.pokerstars.com/poker/games/rules/hand-rankings/.
>
> Which of the following is better and more Pythonic ?
>

Your two code segments will do different things.


>
> def poker(hands):
>     return max(hands, key=hand_rank)
>

In this case, the "hand_rank" function will take a single hand, and return
its rank value. Additionally, the "poker" function will return the highest
ranked hand.


>
> or
>
> def poker(hands):
>     return max(hand_rank(hands))
>

In this case, the "hand_rank" function will take an iterable of hands and
return an iterable of hand ranks. Additionally, the "poker" function will
return the rank of the highest ranked hand.

If that is the desired result, I would recommend writing this as:

def poker(hands):
    return max(map(hand_rank, hands))

which will result in hand_rank taking a single hand and returning its rank
value (similar to the first code segment you provided), rather than having
hand_rank deal with iterables of hands. However, that has more to do with
how you want hand_rank to behave, and where else it might be used.

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


Thread

Re: More Pythonic implementation Chris Kaynor <ckaynor@zindagigames.com> - 2014-08-19 11:57 -0700

csiph-web