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


Groups > comp.lang.python > #76595 > unrolled thread

More Pythonic implementation

Started byShubham Tomar <tomarshubham24@gmail.com>
First post2014-08-19 22:39 +0530
Last post2014-08-20 17:52 +0200
Articles 2 — 2 participants

Back to article view | Back to comp.lang.python


Contents

  More Pythonic implementation Shubham Tomar <tomarshubham24@gmail.com> - 2014-08-19 22:39 +0530
    Re: More Pythonic implementation Thomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de> - 2014-08-20 17:52 +0200

#76595 — More Pythonic implementation

FromShubham Tomar <tomarshubham24@gmail.com>
Date2014-08-19 22:39 +0530
SubjectMore Pythonic implementation
Message-ID<mailman.13161.1408473590.18130.python-list@python.org>

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

Hi,

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 ?

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

or

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

Thanks

[toc] | [next] | [standalone]


#76672

FromThomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de>
Date2014-08-20 17:52 +0200
Message-ID<lt2g7j$c3t$1@r01.glglgl.de>
In reply to#76595
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.

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web