More Pythonic implementation

Chris Kaynor ckaynor at zindagigames.com
Tue Aug 19 14:57:56 EDT 2014


On Tue, Aug 19, 2014 at 10:09 AM, Shubham Tomar <tomarshubham24 at 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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140819/8e58602e/attachment.html>


More information about the Python-list mailing list