zoukankan      html  css  js  c++  java
  • Decks

    Now that we have Card objects, the next step is to define a class to represent decks. Since a deck is made up cards, a natural choice is for each Deck object to contain a list of cards as an attribute. The following is a class definition for Deck. The init method creates the attribute cards and generates the standard set of fifty-two cards:

    class Deck:
        """represents a standard Deck
           instance attributes: cards """
        def __init__(self):
            self.cards = []
            for suit in range(4):
                for rank in range(1,14)
                card = Card(suit,rank)
                self.cards.append(card)

    The easiest way to populate the deck is with a nested loop. The outer loop enumerates the suits from 0 to 3. The inner loop enumerates the ranks from 1 to 13. Each iteration of the inner loop creates a new Card with current suit and rank, and appends it to self.cards.

    Printing the deck

    Here is a str method for Deck:

    def __str__(self):
            temp = []
            for card in self.cards:
                temp.append(str(card))
            return '
    '.join(temp)

    The method demonstrates an efficient way to accumulate a large string, by building a list of strings and then using join. The built-in function str invokes the __str__ method on each card and returns the string representation. Since we invoke join on a newline character, the cards are separated by newlines.

    ........

    from Thinking in Python

     

     

  • 相关阅读:
    Codeforces Round #360 B
    Codeforces Round #360 C
    Codeforces Round #360 D
    新姿势 树剖求LCA
    Codeforces 165D Beard Graph 边权树剖+树状数组
    hdu3966 树链剖分+线段树 裸题
    Codeforces Round #425 D
    Codeforces Round #425 B
    Codeforces Round #425 A
    bzoj 1036 树链剖分+线段树 裸题
  • 原文地址:https://www.cnblogs.com/ryansunyu/p/4008194.html
Copyright © 2011-2022 走看看