2020年1月6日月曜日

Python - Repeating Code Using Loops - range関数(start, stop, step), for loop, total, average

Practical Programming: An Introduction to Computer Science Using Python 3.6 (Paul Gries(著)、Jennifer Campbell(著)、Jason Montojo(著)、Pragmatic Bookshelf)のChapter 9(Repeating Code Using Loops)、Exercise 9、10、11の解答を求めてみる。

コード

```#!/usr/bin/env python3
from unittest import TestCase, main
from test.support import captured_stdout

print('9, 10, 11.')

class MyTestCase(TestCase):

def test9(self):
with captured_stdout() as stdout:
for n in range(33, 49 + 1):
print(n)
s = '''33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
'''
self.assertEqual(stdout.getvalue(), s)

def test10(self):
with captured_stdout() as stdout:
for n in range(10, 0, -1):
print(n, end=' ')
s = '10 9 8 7 6 5 4 3 2 1 '
self.assertEqual(stdout.getvalue(), s)

def test11(self):
total = 0
for n in range(2, 23):
total += n
average = total / (22 - 1)
self.assertEqual(average, sum(range(2, 23)) / len(range(2, 23)))

if __name__ == '__main__':
main()
```

```% ./sample9.py -v
9, 10, 11.
test10 (__main__.MyTestCase) ... ok
test11 (__main__.MyTestCase) ... ok
test9 (__main__.MyTestCase) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK
%
```