zoukankan      html  css  js  c++  java
  • Card objects

    There are fifty-two cards in a deck, each of which belongs to one of four suits and one of thirteen ranks. The suits are Spades, Hearts, Diamonds, and Clubs (in descending order in bridge). The ranks are Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, and King. Depending on the game that you are playing, an Ace may be higher than King or lower than 2.

    If we want to define a new object to represent a playing card, it is obvious what the attributes should be: rank and suit. It is not as obvious what type the attributes should be. One possibility is to use strings containing words like ‘Spade’ for suits and ‘Queen’ for ranks. One problem with this implementation is that it would not be easy to compare cards to see which had a higher rank or suit.

    An alternative is to use integers to encode the ranks and suits. In this context, ‘encode’ means that we are going to define a mapping between numbers and suits, or between numbers and ranks. This kind of encoding is not meant to be a secret.

    For example, this table shows the suits and the corresponding integer codes:

    Spades -> 3

    Hearts -> 2

    Diamonds -> 1

    Clubs -> 0

    This code makes it easy to compare cards; because higher suits map to higher numbers, we can compare suits by comparing their codes.

    The class definition for Card looks like:

    class Card:
        """ represents a standard playing card."""
    
        def __init__(self, suit=0, rank=2):
            self.suit = suit
            self.rank = rank

    As usual, the init method takes an optional parameter for each attribute. The default card is the 2 of Clubs.

    from Thinking in Python

  • 相关阅读:
    前端图片预览
    理解 Promise 过程
    node 小例子 集合
    各大网站处理 高 retina屏 边框 方法
    用js 创建  简单查找 删除 二叉树
    Python_快速安装第三方库-pip
    Python-找字典中公共key-zip reduce lambda
    Python-对字典进行排序
    Python-统计序列中元素
    Python-为元组中每个元素命名
  • 原文地址:https://www.cnblogs.com/ryansunyu/p/4004918.html
Copyright © 2011-2022 走看看