## 2020年3月12日木曜日

### Python - Storing Data Using Other Collection Types - Set, List, Tuple, Dict, Creating New Type Annotations

Practical Programming: An Introduction to Computer Science Using Python 3.6 (Paul Gries(著)、Jennifer Campbell(著)、Jason Montojo(著)、Pragmatic Bookshelf)のChapter 11(Storing Data Using Other Collection Types)、Exercise 1、2の解答を求めてみる。

コード

```#!/usr/bin/env python3
from unittest import TestCase, main
from typing import List, Set, Tuple, Dict, TextIO, Union
from io import StringIO

print('1, 2.')

class TestFindDups(TestCase):
def test_empty(self):
self.assertEqual(find_dups([]), set())

def test_one(self):
self.assertEqual(find_dups([1]), set())

def test_one_dup(self):
self.assertEqual(find_dups([0, 1, 1]), {1})

def test_two_dup(self):
self.assertEqual(find_dups([0, 1, 2, 3, 4, 5, 1, 2, 1, 2, 1]),
{1, 2})

def test(self):
instring = '''COMPND TEST
ATOM 1 N 0.1 0.2 0.3
ATOM 2 N 0.2 0.1 0.0
END
'''
infile = StringIO(instring)
{'TEST': [('N', ('0.1', '0.2', '0.3')),
('N', ('0.2', '0.1', '0.0'))]})

def test(self):
cmpnd1 = '''COMPND T1
ATOM 1 N 0.1 0.2 0.3
ATOM 2 N 0.2 0.1 0.0
END
'''
cmpnd2 = '''COMPND T2
ATOM 1 A 0.1 0.2 0.3
ATOM 2 A 0.2 0.1 0.0
END
'''
infile = StringIO(cmpnd1 + cmpnd2)
{'T1': [('N', ('0.1', '0.2', '0.3')),
('N', ('0.2', '0.1', '0.0'))],
'T2': [('A', ('0.1', '0.2', '0.3')),
('A', ('0.2', '0.1', '0.0'))]})

def find_dups(nums: List[int]) -> Set[int]:
s1: Set = set()
s2: Set = set()
for num in nums:
if num in s1:
return s2

Atom = Tuple[str, Tuple[str, str, str]]
CompoundDict = Dict[str, List[Atom]]

if not line:
return None
parts: List[str] = line.split()
name: str = parts[1]
molecule: CompoundDict = {name: []}
if line.startswith('END'):
break
parts = line.split()
molecule[name].append((parts[2], (parts[3], parts[4], parts[5])))
return molecule

result = {}
while True:
if molecule is None:
break
else:
name = list(molecule.keys())[0]
result[name] = list(molecule.values())[0]
return result

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

```% mypy sample1.py
Success: no issues found in 1 source file
% ./sample1.py -v
1, 2.
test_empty (__main__.TestFindDups) ... ok
test_one (__main__.TestFindDups) ... ok
test_one_dup (__main__.TestFindDups) ... ok
test_two_dup (__main__.TestFindDups) ... ok