zoukankan      html  css  js  c++  java
  • Comparing cards

    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)

    from Thinking in Python

  • 相关阅读:
    NOIP2018 游记
    HDU1556 敌兵布阵
    BZOJ 1032 [JSOI2007]祖码Zuma
    BZOJ 1068 [SCOI2007]压缩
    BZOJ 1090 [SCOI2003]字符串折叠
    BZOJ 1260 [CQOI2007]涂色paint
    BZOJ 1055 [HAOI2008]玩具取名
    HDU 5151 Sit sit sit
    HDU 4283 You Are the One
    vue系列8:webpack
  • 原文地址:https://www.cnblogs.com/ryansunyu/p/4008174.html
Copyright © 2011-2022 走看看