码迷,mamicode.com
首页 > 其他好文 > 详细

Comparing cards

时间:2014-10-06 15:56:40      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   os   ar   for   

For built-in types, there are conditional operators (<, >, ==, etc.) that compare values and determine when one is greater than, less than, or equal to another. For user-defined types, we can override the behavior of the built-in operators by providing a method named __cmp__. But in Python 3+, the cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)

The cmp method takes two parameters, self and other, and returns a positive number if the first object is greater, a negative number is the second object is greater, and 0 if they are equal to each other. The correct ordering for cards is not obvious. For example, which is better, the 3 of Clubs or the 2 of Diamonds? One has a higher rank, but the other has a higher suit. In order to compare cards, you have to decide whether rank or suit is more important.

The answer might depend on what game you are playing, but to keep things simple, we’ll make the arbitrary choice that suit is more important, so all of the Spades outrank all of the Diamonds, and so on.

def cmp(self,other):
        t1 = (self.suit,self.rank)
        t2 = (other.suit,other.rank)
        return (t1 > t2) - (t1 < t2)

bubuko.com,布布扣

 

from Thinking in Python

Comparing cards

标签:des   style   blog   http   color   io   os   ar   for   

原文地址:http://www.cnblogs.com/ryansunyu/p/4008174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!