開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- Python 3.5 (プログラミング言語)
Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 18.(Inheritance)のExercises 18-2.(No. 4220)を取り組んでみる。
Exercises 18-2.(No. 4220)
コード(Emacs)
test
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Card: suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spaces'] rank_names = ( [None, 'Ace'] + list(map(str, range(2, 11))) + ['Jack', 'Queen', 'King'] ) def __init__(self, suit=0, rank=2): self.suit = suit self.rank = rank def __str__(self): return '{0} of {1}'.format(Card.rank_names[self.rank], Card.suit_names[self.suit]) class Deck: def __init__(self): self.cards = [] for suit in range(4): for rank in range(1, 14): card = Card(suit, rank) self.cards.append(card) def deal_hands(self, hands_num, cards_num): hands = [] for i in range(hands_num): hand = Hand() for j in range(cards_num): card = Card() hand.add_card(card) hands.append(hand) return hands def add_card(self, card): self.cards.append(card) def __str__(self): res = [] for card in self.cards: res.append(str(card)) return '\n'.join(res) class Hand(Deck): def __init__(self, label=''): self.cards = [] self.label = label if __name__ == '__main__': deck = Deck() hands = deck.deal_hands(2, 3) for i, hand in enumerate(hands): print(i) print(hand)
入出力結果(Terminal, IPython)
$ ./sample2.py 0 2 of Clubs 2 of Clubs 2 of Clubs 1 2 of Clubs 2 of Clubs 2 of Clubs $
0 コメント:
コメントを投稿