## 2018年6月10日日曜日

### Python - 数学 - 集合と確率を操作する - トランプをよく切る(randomモジュール、shuffleメソッド、リスト)

Pythonからはじめる数学入門 (Amit Saha (著)、黒川 利明 (翻訳)、オライリージャパン)の5章(集合と確率を操作する)、5.4(プログラミングチャレンジ)、問題5-4(トランプをよく切る)を取り組んでみる。

コード(Emacs)

Python 3

```#!/usr/bin/env python3
import random

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

def __str__(self):
d = {11: 'jack', 12: 'queen', 13: 'king'}
return f'{d.get(self.rank, self.rank)} of {self.suit}'

if __name__ == '__main__':
cards = [Card(suit, rank)
for suit in ['diamonds', 'clubs', 'hearts', 'spades']
for rank in range(1, 14)]
for card in cards:
print(card)
random.shuffle(cards)
print('shuffled')
for card in cards:
print(card)
```

```\$ ./sample4.py
1 of diamonds
2 of diamonds
3 of diamonds
4 of diamonds
5 of diamonds
6 of diamonds
7 of diamonds
8 of diamonds
9 of diamonds
10 of diamonds
jack of diamonds
queen of diamonds
king of diamonds
1 of clubs
2 of clubs
3 of clubs
4 of clubs
5 of clubs
6 of clubs
7 of clubs
8 of clubs
9 of clubs
10 of clubs
jack of clubs
queen of clubs
king of clubs
1 of hearts
2 of hearts
3 of hearts
4 of hearts
5 of hearts
6 of hearts
7 of hearts
8 of hearts
9 of hearts
10 of hearts
jack of hearts
queen of hearts
king of hearts
shuffled
9 of diamonds
3 of diamonds
2 of diamonds
3 of hearts
2 of clubs
jack of diamonds
1 of hearts
6 of diamonds
7 of hearts
5 of hearts
7 of clubs
10 of hearts
4 of hearts
queen of diamonds
king of clubs
10 of clubs
king of hearts
7 of diamonds
8 of clubs
queen of clubs
10 of diamonds
6 of hearts
5 of clubs
6 of clubs
jack of hearts
9 of clubs
queen of hearts
3 of clubs
1 of clubs
8 of hearts
2 of hearts
1 of diamonds
4 of diamonds
4 of clubs
8 of diamonds
jack of clubs