開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
Head First はじめてのプログラミング ―頭とからだで覚えるPythonプログラミング入門 (Eric Freeman(著)、嶋田 健志(監修)、木下 哲也(翻訳)、株式会社オライリー・ジャパン)をおまけの章(ソートと入れ子の反復 - リストに戻って強力な能力を追加する - データを整理する)のインタプリタになってみよう(233ページ)の解答を求めてみる。
コード
Python 3
#!/usr/bin/env python3
from unittest import TestCase, main
from test.support import captured_stdout
import math
class MyTestCase(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test1(self):
s = '''0
0
0
0
0
1
2
3
0
2
4
6
0
3
6
9
'''
with captured_stdout() as stdout:
for i in range(4):
for j in range(4):
print(i * j)
self.assertEqual(stdout.getvalue(), s)
def test2(self):
s = '''2 ox
3 cat
2 lion
4 lion
5 tiger
2 bobcat
3 bobcat
6 bobcat
'''
with captured_stdout() as stdout:
for word in ['ox', 'cat', 'lion', 'tiger', 'bobcat']:
for i in range(2, 7):
letters = len(word)
if letters % i == 0:
print(i, word)
self.assertEqual(stdout.getvalue(), s)
def test3(self):
full = False
donations = []
full_load = 45
toys = ['ロボット', '人形', 'ボール', 'スリンキー']
while not full:
for toy in toys:
for toy in toys:
donations.append(toy)
size = len(donations)
if size >= full_load:
full = True
self.assertEqual(len(donations), 48)
self.assertEqual(donations,
toys *
math.ceil(full_load / len(toys)))
if __name__ == '__main__':
main()
入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal、Jupyter(IPython))
C:\Users\...>py sample2.py ... ---------------------------------------------------------------------- Ran 3 tests in 0.000s OK C:\Users\...>
0 コメント:
コメントを投稿