開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- Python 3.6 (プログラミング言語)
行列プログラマー(Philip N. Klein (著)、 松田 晃一 (翻訳)、 弓林 司 (翻訳)、 脇本 佑紀 (翻訳)、 中田 洋 (翻訳)、 齋藤 大吾 (翻訳)、オライリージャパン)の1章(ベクトル)、2.9(ドット積)、類似性の測定、クイズ 2.9.15を取り組んでみる。
クイズ 2.9.15
コード(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]) if __name__ == '__main__': unittest.main()
入出力結果(Terminal, IPython)
$ ./sample9_15.py -v test_dot_product_list0 (__main__.Test) ... ok test_dot_product_list1 (__main__.Test) ... ok test_dot_product_list2 (__main__.Test) ... ok ---------------------------------------------------------------------- Ran 3 tests in 0.000s OK $
0 コメント:
コメントを投稿