開発環境
- macOS Mojave - Apple
- Emacs (Text Editor)
- Python 3.7 (プログラミング言語)
問題解決のPythonプログラミング ―数学パズルで鍛えるアルゴリズム的思考 (Srini Devadas (著)、黒川 利明 (翻訳)、オライリージャパン)の2章(パーティーに行くタイミング)、練習問題(問題2)を取り組んでみる。
コード(Emacs)
Python 3
#!/usr/bin/env python3 ''' 問題2 ''' def best_time_to_party_smart(schedule: list) -> float: ''' >>> sched = [(6, 8), (6, 12), (6, 7), (7, 8), (7, 10), (8, 9), (8, 10), ... (9, 12), (9, 10), (10, 11), (10, 12), (11, 12)] >>> sched2 = [(6.0, 8.0), (6.5, 12.0), (6.5, 7.0), (7.0, 8.0), (7.5, 10.0), ... (8.0, 9.0), (8.0, 10.0), (9.0, 12.0), (9.5, 10.0), ... (10.0, 11.0), (10.0, 12.0), (11.0, 12.0)] >>> best_time_to_party_smart(sched) (9, 5) >>> best_time_to_party_smart(sched2) (9.5, 5) ''' time = schedule[0][0] maxcount = 1 for i, (start, _) in enumerate(schedule): count = 1 for start1, end1 in schedule[:i] + schedule[i + 1:]: if start1 <= start < end1: count += 1 if count > maxcount: time = start maxcount = count return time, maxcount if __name__ == '__main__': import doctest doctest.testmod()
入出力結果(Terminal, Jupyter(IPython))
$ ./sample2.py $ ./sample2.py -v (9, 5) (9.5, 5) Trying: sched = [(6, 8), (6, 12), (6, 7), (7, 8), (7, 10), (8, 9), (8, 10), (9, 12), (9, 10), (10, 11), (10, 12), (11, 12)] Expecting nothing ok Trying: sched2 = [(6.0, 8.0), (6.5, 12.0), (6.5, 7.0), (7.0, 8.0), (7.5, 10.0), (8.0, 9.0), (8.0, 10.0), (9.0, 12.0), (9.5, 10.0), (10.0, 11.0), (10.0, 12.0), (11.0, 12.0)] Expecting nothing ok Trying: best_time_to_party_smart(sched) Expecting: (9, 5) ok Trying: best_time_to_party_smart(sched2) Expecting: (9.5, 5) ok 1 items had no tests: __main__ 1 items passed all tests: 4 tests in __main__.best_time_to_party_smart 4 tests in 2 items. 4 passed and 0 failed. Test passed. $ pylint sample2.py ************* Module sample2 sample2.py:11:59: C0303: Trailing whitespace (trailing-whitespace) ------------------------------------------------------------------ Your code has been rated at 9.33/10 $ pylint sample2.py ------------------------------------------------------------------- Your code has been rated at 10.00/10 (previous run: 9.33/10, +0.67) $
0 コメント:
コメントを投稿