2018年11月13日火曜日

開発環境

問題解決のPythonプログラミング ―数学パズルで鍛えるアルゴリズム的思考 (Srini Devadas (著)、黒川 利明 (翻訳)、オライリージャパン)の3章(心を読む(準備をしてから))、練習問題(問題1)を取り組んでみる。

コード(Emacs)

Python 3

#!/usr/bin/env python3
''' 問題 '''
deck = [f'{num}_{suit}'
        for num in ['A'] + list(range(2, 11)) + ['J', 'Q', 'K']
        for suit in ['C', 'D', 'H', 'S']]

print('deck')
for i, card in enumerate(deck):
    print(card, end=' ')
    if i % 4 == 3:
        print()


def check(cards):
    for i, card1 in enumerate(cards):
        for card2 in cards[i + 1:]:
            if card1 == card2:
                return False
    return True


def computer_assistant(number):
    # number = int(input('Please give random number of at least 6 digits: '))
    '''
    >>> check(computer_assistant(888888))
    True
    '''
    cards = []
    i = 0
    while len(cards) < 5:
        number = number * (i + 1) // (i + 2)
        n = number % 52
        card_new = deck[n]
        if card_new not in cards:
            cards.append(card_new)
        i += 1
    return cards


if __name__ == '__main__':
    import doctest
    doctest.testmod()

入出力結果(Terminal, Jupyter(IPython))

$ ./sample1.py
deck
A_C A_D A_H A_S 
2_C 2_D 2_H 2_S 
3_C 3_D 3_H 3_S 
4_C 4_D 4_H 4_S 
5_C 5_D 5_H 5_S 
6_C 6_D 6_H 6_S 
7_C 7_D 7_H 7_S 
8_C 8_D 8_H 8_S 
9_C 9_D 9_H 9_S 
10_C 10_D 10_H 10_S 
J_C J_D J_H J_S 
Q_C Q_D Q_H Q_S 
K_C K_D K_H K_S 
Trying:
    check(computer_assistant(888888))
Expecting:
    True
ok
2 items had no tests:
    __main__
    __main__.check
1 items passed all tests:
   1 tests in __main__.computer_assistant
1 tests in 3 items.
1 passed and 0 failed.
Test passed.
$

0 コメント:

コメントを投稿

関連コンテンツ