More Pythonic implementation

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Wed Aug 20 11:52:14 EDT 2014


Am 19.08.2014 19:09 schrieb Shubham Tomar:

> 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 ?

They are different.


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

This one determines the hands element with the biggest hand_rank(i) 
value and returns it, while

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

returns the hand_rank value, but only if hand_rank() is applicable to 
lists. Otherwise, it fails.


hands = [1, 2, 3, 4, 5]

def hand_rank(i): return -i

So,

max(hands, key=hand_rank)

gives 1 because it has the biggest hand_rank(value) of -1 in the range 
of -5..-1.

OTOH,

max(hand_rank(hands))

will fail, because there is no list.__neg__(). If there was, it would be 
the same as max([-1, -2, -3, -4, -5]), so it would be -1 itself.



More information about the Python-list mailing list