## 2020年3月29日日曜日

### Python - Storing Data Using Other Collection Types - sparse vectors, メモリの節約, list, dictionary, addition, dot product

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

コード

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

print('12.')

class TestSparse(TestCase):
def setUp(self):
self.sparse_vect1 = {0: 1, 1: 2, 2: 3}
self.sparse_vect2 = {0: 4, 1: 5, 2: 6}

{0: 5, 1: 7, 2: 9})

def test_sparse_dot(self):
self.assertEqual(sparse_dot(self.sparse_vect1, self.sparse_vect2),
32)

sparse_vect2: Dict[int, int]) -> Dict[int, int]:
result = sparse_vect1.copy()
for k, v in sparse_vect2.items():
result.setdefault(k, 0)
result[k] += v
return result

def sparse_dot(sparse_vect1: Dict[int, int],
sparse_vect2: Dict[int, int]) -> int:
result = 0
for k in set(sparse_vect1.keys()) | set(sparse_vect2.keys()):
v1 = sparse_vect1.get(k, 0)
v2 = sparse_vect2.get(k, 0)
result += v1 * v2
return result

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

```% mypy sample12.py
Success: no issues found in 1 source file
% ./sample12.py -v
12.