2016年2月24日水曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Python 3.5 (プログラミング言語)

Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More! (Amit Saha (著)、No Starch Press)のChapter 5.(Playing with Sets and Probability)、Programming Challenges #4: Shuffling a Deck of Cards(No. 3636)を解いてみる。

#4: Shuffling a Deck of Cards(No. 3636)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import random

SUITS = ['spades', 'hearts', 'diamnds', 'clubs']
RANKS = ['ace'] + [str(n) for n in range(2, 11)] + ['jack', 'queen', 'king']


class Card:

    def __init__(self, suit, rank):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        return '{0} of {1}'.format(self.rank, self.suit)


if __name__ == '__main__':
    CARDS = [Card(suit, rank) for suit in SUITS for rank in RANKS]
    for _ in range(10):
        random.shuffle(CARDS)
        print('shuffled--------------------------------------------------')
        for card in CARDS[:5]:
            print(card)

入出力結果(Terminal, IPython)

$ ./sample4.py
shuffled--------------------------------------------------
10 of spades
4 of hearts
5 of diamnds
9 of hearts
3 of spades
shuffled--------------------------------------------------
jack of clubs
3 of clubs
king of hearts
9 of hearts
8 of clubs
shuffled--------------------------------------------------
4 of clubs
ace of spades
ace of hearts
6 of diamnds
9 of hearts
shuffled--------------------------------------------------
4 of spades
5 of hearts
5 of spades
9 of spades
9 of hearts
shuffled--------------------------------------------------
10 of clubs
8 of diamnds
8 of hearts
2 of spades
5 of spades
shuffled--------------------------------------------------
jack of diamnds
8 of hearts
2 of clubs
9 of hearts
king of diamnds
shuffled--------------------------------------------------
2 of clubs
6 of clubs
6 of spades
jack of diamnds
3 of diamnds
shuffled--------------------------------------------------
queen of diamnds
4 of hearts
7 of hearts
jack of diamnds
9 of diamnds
shuffled--------------------------------------------------
8 of spades
5 of hearts
king of clubs
7 of clubs
10 of hearts
shuffled--------------------------------------------------
king of spades
ace of spades
queen of diamnds
4 of diamnds
10 of spades
$

0 コメント:

コメントを投稿

Comments on Google+: