More Pythonic implementation
Ben Finney
ben+python at benfinney.id.au
Tue Aug 19 19:41:58 EDT 2014
Shubham Tomar <tomarshubham24 at gmail.com> writes:
> 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.
To make it clearer, I think you mean something like this::
def hand_rank(hand):
""" Determine the rank of the poker hand. """
rank = int(some_complex_computation(hand))
return rank
In other words, I'm assuming ‘hand_rank’ returns an integer.
> Which of the following is better and more Pythonic ?
Only one of them does anything useful :-)
> def poker(hands):
> return max(hands, key=hand_rank)
This will return the item from the collection ‘hand’ with the maximum
value as determined by ‘hand_rank’. So this appears to do what you want.
> def poker(hands):
> return max(hand_rank(hands))
This raises “TypeError: 'int' object is not iterable” because you're
operating on one return value from ‘hand_rank’, which is not a
collection.
--
\ “Corporation, n. An ingenious device for obtaining individual |
`\ profit without individual responsibility.” —Ambrose Bierce, |
_o__) _The Devil's Dictionary_, 1906 |
Ben Finney
More information about the Python-list
mailing list