開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
Practical Programming: An Introduction to Computer Science Using Python 3.6 (Paul Gries(著)、Jennifer Campbell(著)、Jason Montojo(著)、Pragmatic Bookshelf)のChapter 5(Making Choices)、Exercises 7の解答を求めてみる。
コード
Python 3
#!/usr/bin/env python3
from unittest import TestCase, main
from test.support import captured_stdout
class MyTestCase(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_a(self):
populations = [9999999, 10000000]
with captured_stdout() as stdout:
for population in populations:
if population < 10000000:
print(population)
self.assertEqual(stdout.getvalue(), '9999999\n')
def test_b(self):
populations = [9999999, 10000000, 35000000, 35000001]
with captured_stdout() as stdout:
for population in populations:
if 10000000 <= population <= 35000000:
print(population)
s = '''10000000
35000000
'''
self.assertEqual(stdout.getvalue(), s)
def test_c(self):
population = 10000
areas = [1, 10, 100, 1000]
with captured_stdout() as stdout:
for area in areas:
if population / area > 100:
# print('Densely populated')
print(area)
s = '''1
10
'''
self.assertEqual(stdout.getvalue(), s)
def test_d(self):
population = 10000
areas = [1, 10, 100, 1000]
with captured_stdout() as stdout:
for area in areas:
if population / area > 100:
print('Densely populated')
else:
print('Sparsely populated')
s = '''Densely populated
Densely populated
Sparsely populated
Sparsely populated
'''
self.assertEqual(stdout.getvalue(), s)
if __name__ == '__main__':
main()
入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal、Jupyter(IPython))
$ ./sample7.py -v test_a (__main__.MyTestCase) ... ok test_b (__main__.MyTestCase) ... ok test_c (__main__.MyTestCase) ... ok test_d (__main__.MyTestCase) ... ok ---------------------------------------------------------------------- Ran 4 tests in 0.000s OK $
0 コメント:
コメントを投稿