開発環境
- macOS Mojave - Apple
- Emacs (Text Editor)
- Python 3.7 (プログラミング言語)
問題解決のPythonプログラミング ―数学パズルで鍛えるアルゴリズム的思考 (Srini Devadas (著)、黒川 利明 (翻訳)、オライリージャパン)の1章(帽子を全員で揃える)、練習問題、問題1.を取り組んでみる。
コード(Emacs)
Python 3
#!/usr/bin/env python3 caps1 = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'B', 'F'] caps2 = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'F', 'F'] def please_conform(caps): start = 0 forward = 0 backward = 0 intervals = [] for i in range(1, len(caps)): if caps[start] != caps[i]: intervals.append((start, i - 1, caps[start])) if caps[start] == 'F': forward += 1 else: backward += 1 start = i intervals.append((start, len(caps) - 1, caps[start])) if caps[start] == 'F': forward += 1 else: backward += 1 if forward < backward: flip = 'F' else: flip = 'B' # 修正箇所 for t in intervals: if t[2] == flip: if t[0] == t[1]: print(f'Person at position {t[0]} flip your cap!') else: print( f'People in positions {t[0]} through {t[1]} flip your caps!' ) for cap in [caps1, caps2]: please_conform(cap) print()
入出力結果(Terminal, Jupyter(IPython))
$ ./sample1.py 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! People in positions 2 through 4 flip your caps! People in positions 6 through 8 flip your caps! $
0 コメント:
コメントを投稿