forked from wcmac/sippycup
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathexecutor.py
More file actions
50 lines (39 loc) · 1.36 KB
/
Copy pathexecutor.py
File metadata and controls
50 lines (39 loc) · 1.36 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
import unittest
class Executor(object):
"""
Performs the arithmetic calculations described by semantic representations
to return a denotation.
"""
def __init__(self):
super(Executor, self).__init__()
# Map operations to functions that execute them on arguments
ops = {
'~': lambda x: -x,
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
}
@staticmethod
def execute(sem):
if isinstance(sem, tuple):
op = Executor.ops[sem[0]] # Get the operator function
# Collect the values of the arguments
args = []
for arg in sem[1:]:
args.append(Executor.execute(arg))
# Call the operator function on the arguments
return op(*args)
else:
return sem
class TestMethods(unittest.TestCase):
def test_one_plus_one(self):
self.assertEqual(2, Executor.execute(('+', 1, 1)))
def test_minus_three_minus_two(self):
self.assertEqual(-5, Executor.execute(('-', ('~', 3), 2)))
def test_three_plus_three_minus_two(self):
self.assertEqual(4, Executor.execute(('-', ('+', 3, 3), 2)))
def test_two_times_two_plus_three(self):
self.assertEqual(7, Executor.execute(('+', ('*', 2, 2), 3)))
# SLIDES
if __name__ == "__main__":
unittest.main()