-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patht6_infix_operator_a.py
More file actions
58 lines (40 loc) · 1.43 KB
/
Copy patht6_infix_operator_a.py
File metadata and controls
58 lines (40 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env python
from __future__ import division
import itertools
from operator import mul
import unittest
class PartiallyAppliedInfix(object):
def __init__(self, f, left_argument):
self.f = f
self.left_argument = left_argument
def __or__(self, right_argument):
return self.f(self.left_argument, right_argument)
class Infix(object):
def __init__(self, f):
self.f = f
def __ror__(self, left_argument):
return PartiallyAppliedInfix(self.f, left_argument)
def make_infix(f):
"""
Make function possible to be used this way:
i_f = make_infix(f)
f(a,b) <=> a |i_f| b
"""
return Infix(f)
class Tests(unittest.TestCase):
def setUp(self):
def dot_product(x, y): return sum(itertools.starmap(mul, itertools.izip(x, y)))
self.dot_product = dot_product
self.dot = make_infix(self.dot_product)
def cross_product(x,y): return list(itertools.starmap(mul, itertools.izip(x, y)))
self.cross_product = cross_product
self.cross = make_infix(self.cross_product)
def test_double(self):
A = [1, 2, 3, 4, 5]
B = [1, 2, 3, 4, 5]
self.assertEqual(A |self.dot| B, self.dot_product(A,B))
def test_tripple(self):
A = [1, 2, 3, 4, 5]
B = [1, 2, 3, 4, 5]
C = [7, 8, 9, 10, 11]
self.assertEqual(A |self.cross| B |self.cross| C, self.cross_product(self.cross_product(A,B),C))