開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
Head First はじめてのプログラミング ―頭とからだで覚えるPythonプログラミング入門 (Eric Freeman(著)、嶋田 健志(監修)、木下 哲也(翻訳)、株式会社オライリー・ジャパン)を8章(再帰と辞書 - 反復とインデックスを超えて)の自分で考えてみよう(353ページ)の解答を求めてみる。
コード
Python 3
#!/usr/bin/env python3
from unittest import TestCase, main
from test.support import captured_stdout
from typing import List
class SampleTestCase(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test(self):
# フレーム3、2、1
s = '''lst = [3]
first = 3
rest = []
lst = [2, 3]
first = 2
rest = [3]
lst = [1, 2, 3]
first = 1
rest = [2, 3]
'''
with captured_stdout() as stdout:
recursive_compute_sum([1, 2, 3])
self.assertEqual(stdout.getvalue(), s)
def recursive_compute_sum(lst: List[int]) -> int:
if not lst:
return 0
first: int = lst[0]
rest: List[int] = lst[1:]
sums: int = first + recursive_compute_sum(rest)
print(f'lst = {lst}\nfirst = {first}\nrest = {rest}')
return sums
if __name__ == '__main__':
main()
入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal、Jupyter(IPython))
$ ./sample2.py . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK $
0 コメント:
コメントを投稿