## 2019年12月22日日曜日

### Python - Repeating Code Using Loops - list, for loop

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 1、2、3の解答を求めてみる。

コード

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

class MyTestCase(TestCase):
def test1(self):
celegans_phenotypes = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma']
s = '''Emb
Him
Unc
Lon
Dpy
Sma
'''
with captured_stdout() as stdout:
for t in celegans_phenotypes:
print(t)
self.assertEqual(stdout.getvalue(), s)

def test2(self):
half_lives = [87.74, 24110.0, 653.0, 14.4, 376000.0]

s = '87.74 24110.0 653.0 14.4 376000.0 '
with captured_stdout() as stdout:
for l in half_lives:
print(l, end=' ')
self.assertEqual(stdout.getvalue(), s)

def test3(self):
whales = [5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, 7, 1, 3]
more_wahles = []
for whale in whales:
more_wahles.append(whale + 1)
self.assertEqual(
more_wahles, [6, 5, 8, 4, 3, 4, 3, 7, 5, 3, 2, 8, 2, 4])

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

```% ./sample1.py -v
test1 (__main__.MyTestCase) ... ok
test2 (__main__.MyTestCase) ... ok
test3 (__main__.MyTestCase) ... ok

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

OK
%
```