## 2020年1月11日土曜日

### Python - Repeating Code Using Loops - nested for loops, print triangles, hypotenuses, right side, left side

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 13、14の解答を求めてみる。

コード

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

print('13, 14.')

size = 7

class NestedForLoopsTestCase(TestCase):
def test13(self):
s: str = '''T
TT
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
'''
with captured_stdout() as stdout:
for i in range(size):
for _ in range(i + 1):
print('T', end='')
print()
self.assertEqual(stdout.getvalue(), s)

def test14(self):
s: str = '''      T
TT
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
'''
with captured_stdout() as stdout:
for i in range(size):
for _ in range(size - (i + 1)):
print(' ', end='')
for _ in range(i + 1):
print('T', end='')
print()
self.assertEqual(stdout.getvalue(), s)

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

```% ./sample13.py -v
13, 14.
test13 (__main__.NestedForLoopsTestCase) ... ok
test14 (__main__.NestedForLoopsTestCase) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
%
```