2017年4月12日水曜日

開発環境

行列プログラマー(Philip N. Klein (著)、 松田 晃一 (翻訳)、 弓林 司 (翻訳)、 脇本 佑紀 (翻訳)、 中田 洋 (翻訳)、 齋藤 大吾 (翻訳)、オライリージャパン)の2章(ベクトル)、2.9(ドット積)、2.9.8(ドット積の代数的性質)、問題2.9.24、2.9.26 を取り組んでみる。

問題2.9.24、2.9.26

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import unittest


class Vector:

    def __init__(self, labels, function):
        self.D = labels
        self.f = function


def zero_vector(D):
    labels = D
    function = {k: 0 for k in labels}
    return Vector(labels, function)


def get_item(v, d):
    return v.f.get(d, 0)


def scalar_mul(v, alpha):
    return Vector(v.D, {d: x * alpha for d, x in v.f.items()})


def add(u, v):
    D = u.D | v.D
    return Vector(D, {d: get_item(u, d) + get_item(v, d) for d in D
                      if (get_item(u, d) + get_item(v, d)) != 0})


def neg(v):
    return Vector(v.D, {d: -1 * get_item(v, d) for d in v.D})


def dot(u, v):
    return sum([get_item(u, d) * get_item(v, d) for d in u.D | v.D])


def list_dot(u, v):
    return sum([x * v[i] for i, x in enumerate(u)])


def dot_product_list(needle, haystack):
    l = len(needle)
    return [list_dot(needle, haystack[i:i + l])
            for i in range(len(haystack) - len(needle) + 1)]


class Test(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_dot_product_list0(self):
        needle = []
        haystack = [1]
        result = dot_product_list(needle, haystack)
        self.assertEqual(result, [0, 0])

    def test_dot_product_list1(self):
        needle = [2]
        haystack = [3, 4, 5]
        result = dot_product_list(needle, haystack)
        self.assertEqual(result, [6, 8, 10])

    def test_dot_product_list2(self):
        needle = [2, 3]
        haystack = [4, 5, 6]
        result = dot_product_list(needle, haystack)
        self.assertEqual(result, [23, 28])

    def test_9_24(self):
        u = Vector({'A', 'B', 'C', 'D', 'E'}, {'A': 5, 'B': 10})
        v = Vector({'A', 'B', 'C', 'D', 'E'}, {'B': 15, 'C': 20})
        alpha = 100
        a = dot(scalar_mul(u, alpha), scalar_mul(v, alpha))
        b = alpha * dot(u, v)
        self.assertNotEqual(a, b)

    def test_9_26(self):
        u = Vector({'A', 'B', 'C', 'D', 'E'}, {'A': 5, 'B': 10})
        v = Vector({'A', 'B', 'C', 'D', 'E'}, {'B': 15, 'C': 20})
        w = u
        x = v
        a = dot(add(u, v), add(w, x))
        b = dot(u, w) + dot(v, x)
        self.assertNotEqual(a, b)

if __name__ == '__main__':
    unittest.main()

入出力結果(Terminal, IPython)

$ ./sample9_24.py -v
test_9_24 (__main__.Test) ... ok
test_9_26 (__main__.Test) ... ok
test_dot_product_list0 (__main__.Test) ... ok
test_dot_product_list1 (__main__.Test) ... ok
test_dot_product_list2 (__main__.Test) ... ok

----------------------------------------------------------------------
Ran 5 tests in 0.000s

OK
$

0 コメント:

コメントを投稿