2020年3月29日日曜日

開発環境

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}

    def test_parse_add(self):
        self.assertEqual(sparse_add(self.sparse_vect1, self.sparse_vect2),
                         {0: 5, 1: 7, 2: 9})

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


def sparse_add(sparse_vect1: Dict[int, int],
               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()

入出力結果(Zsh、PowerShell、Terminal、Jupyter(IPython))

% mypy sample12.py 
Success: no issues found in 1 source file
% ./sample12.py -v
12.
test_parse_add (__main__.TestSparse) ... ok
test_sparse_dot (__main__.TestSparse) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
%

0 コメント:

コメントを投稿