2020年3月14日土曜日

Python - Storing Data Using Other Collection Types - dictionary(valuesメソッド、itemsメソッド)、color balance、Set(共通部分)、Tuple

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

コード

```#!/usr/bin/env python3
from unittest import TestCase, main
from typing import Dict
import random

print('7, 8, 9.')

class TestCountDuplicates(TestCase):
def test_empty_dict(self):
self.assertEqual(count_duplicate({}), 0)

def test_empty(self):
self.assertEqual(count_duplicate({'a': 1, 'b': 2}), 0)

def test_one(self):
self.assertEqual(count_duplicate(dict(a=1, b=1)), 1)

def test_one1(self):
self.assertEqual(count_duplicate(dict(a=1, b=1, c=1)), 1)

def test_one2(self):
self.assertEqual(count_duplicate(dict(a=1, b=2, c=1, d=3, e=1)), 1)

def test_two(self):
self.assertEqual(count_duplicate(
dict(a=1, b=2, c=3, d=2, e=3, f=2, g=4)), 2)

class TestIsBalanced(TestCase):
def test_true(self):
self.assertTrue(is_balanced(dict(R=0.1, G=0.2, B=0.7)))

def test_false(self):
self.assertFalse(is_balanced(dict(R=0.2, G=0.2, B=0.7)))

def test_random(self):
for _ in range(100):
color = {'R': round(random.random(), 1),
'G': round(random.random(), 1),
'B': round(random.random(), 1)}
if color['R'] + color['G'] + color['B'] == 1:
self.assertTrue(is_balanced(color))
else:
self.assertFalse(is_balanced(color))

class TestDictIntersect(TestCase):
def test_empty(self):
self.assertEqual(dict_intersect(dict(a=1, b=2), dict(a=2, b=3)), {})

def test_one(self):
self.assertEqual(
dict_intersect(dict(a=1, b=2), dict(c=3, b=2)), dict(b=2))

def test_two(self):
self.assertEqual(
dict_intersect(dict(a=1, b=2, c=3, d=4),
dict(a=2, b=2, c=3, d=1, e=2, f=5)),
dict(b=2, c=3)
)

def count_duplicate(d: dict) -> int:
s1 = set()
s2 = set()
for value in d.values():
if value in s1:
return len(s2)

def is_balanced(color: Dict[str, float]) -> bool:
return sum(color.values()) == 1

def dict_intersect(d1: dict, d2: dict) -> dict:
return dict(set(d1.items()) & set(d2.items()))

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

```% ./sample7.py -v
7, 8, 9.
test_empty (__main__.TestCountDuplicates) ... ok
test_empty_dict (__main__.TestCountDuplicates) ... ok
test_one (__main__.TestCountDuplicates) ... ok
test_one1 (__main__.TestCountDuplicates) ... ok
test_one2 (__main__.TestCountDuplicates) ... ok
test_two (__main__.TestCountDuplicates) ... ok
test_empty (__main__.TestDictIntersect) ... ok
test_one (__main__.TestDictIntersect) ... ok
test_two (__main__.TestDictIntersect) ... ok
test_false (__main__.TestIsBalanced) ... ok
test_random (__main__.TestIsBalanced) ... ok
test_true (__main__.TestIsBalanced) ... ok

----------------------------------------------------------------------
Ran 12 tests in 0.002s

OK
%
```