## 2020年1月1日水曜日

### Python - Repeating Code Using Loops - nested list, type annotations

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

コード

```#!/usr/bin/env python3
from unittest import TestCase, main
from typing import List
print('4.')
alkaline_earth_metals: List[List] = [[4, 9.012],
[12, 24.305],
[20, 40.078],
[38, 87.62],
[56, 137.327],
[88, 226]]

for number, weight in alkaline_earth_metals:
print(f'number: {number}, weight: {weight}')

class MyTestCase(TestCase):

def test_c1(self):
number_and_weight = []
for nw in alkaline_earth_metals:
number_and_weight += nw
self.assertEqual(number_and_weight,
[4, 9.012, 12, 24.305, 20, 40.078, 38, 87.62, 56, 137.327, 88, 226])

def test_c2(self):
number_and_weight = []
for number, weight in alkaline_earth_metals:
number_and_weight.append(number)
number_and_weight.append(weight)
self.assertEqual(number_and_weight,
[4, 9.012, 12, 24.305, 20, 40.078, 38, 87.62, 56, 137.327, 88, 226])

print('5.')

def mystery_function(values: List[List]) -> List:
result: List[List] = []
for sublist in values:
result.append([sublist[0]])
for i in sublist[1:]:
result[-1].insert(0, i)
return result

class MyTestCase5MysteryFunction(TestCase):
def test_empty(self):
self.assertEqual(mystery_function([]), [])

def test_one(self):
self.assertEqual(mystery_function(
[[1, 2, 3, 4, 5]]), [[5, 4, 3, 2, 1]])

def test_two(self):
values: List[List] = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
self.assertEqual(mystery_function(values),
[[5, 4, 3, 2, 1], [10, 9, 8, 7, 6]])

def test_other(self):
self.assertEqual(mystery_function([[1, 2], [3, 4], [5, 6], [7, 8, 9, 10]]),
[[2, 1], [4, 3], [6, 5], [10, 9, 8, 7]])

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

```% mypy sample4.py
Success: no issues found in 1 source file
% ./sample4.py -v
4.
number: 4, weight: 9.012
number: 12, weight: 24.305
number: 20, weight: 40.078
number: 38, weight: 87.62
number: 56, weight: 137.327
number: 88, weight: 226
5.
test_c1 (__main__.MyTestCase) ... ok
test_c2 (__main__.MyTestCase) ... ok
test_empty (__main__.MyTestCase5MysteryFunction) ... ok
test_one (__main__.MyTestCase5MysteryFunction) ... ok
test_other (__main__.MyTestCase5MysteryFunction) ... ok
test_two (__main__.MyTestCase5MysteryFunction) ... ok

----------------------------------------------------------------------
Ran 6 tests in 0.001s

OK
%
```