2018年11月7日水曜日

開発環境

問題解決のPythonプログラミング ―数学パズルで鍛えるアルゴリズム的思考 (Srini Devadas (著)、黒川 利明 (翻訳)、オライリージャパン)の1章(帽子を全員で揃える)、練習問題、問題2.を取り組んでみる。

コード(Emacs)

Python 3

#!/usr/bin/env python3

caps1 = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'B', 'F']
caps2 = ['F', 'B', 'F', 'B', 'B', 'B', 'F', 'B', 'F', 'B', 'B', 'F', 'F']
case3 = []
case4 = ['F']


def please_conform_one_pass(caps):
    if 0 <= len(caps) <= 1:
        return
    caps = caps + [caps[0]]
    start_i = 0
    for i in range(1, len(caps)):
        if caps[i] != caps[i - 1]:
            if caps[i] != caps[0]:
                start_i = i
            elif start_i == i - 1:
                print(f'Person at position {i - 1} flip your cap!')
            else:
                print(f'People in positions {start_i}'
                      f' through {i - 1} flip your caps!')


for caps in [caps1, caps2, case3, case4]:
    print(caps)
    please_conform_one_pass(caps)
    print()

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

$ ./sample2.py
['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'B', 'F']
People in positions 2 through 4 flip your caps!
People in positions 6 through 8 flip your caps!
Person at position 11 flip your cap!

['F', 'B', 'F', 'B', 'B', 'B', 'F', 'B', 'F', 'B', 'B', 'F', 'F']
Person at position 1 flip your cap!
People in positions 3 through 5 flip your caps!
Person at position 7 flip your cap!
People in positions 9 through 10 flip your caps!

[]

['F']

$

0 コメント:

コメントを投稿

Comments on Google+: