-
Notifications
You must be signed in to change notification settings - Fork 0
/
Nodes.py
50 lines (36 loc) · 1.3 KB
/
Nodes.py
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
class Node:
def __init__(self, value, children):
self.value = value # value of the node, can be int or str
self.children = children # list of Node
def evaluate(self):
return self.value
class IntVal(Node):
def __init__(self, value):
super().__init__(value, [])
def evaluate(self):
return self.value
class BinOp(Node):
def __init__(self, value, children):
super().__init__(value, children)
def evaluate(self):
if self.value == "+":
return self.children[0].evaluate() + self.children[1].evaluate()
if self.value == "-":
return self.children[0].evaluate() - self.children[1].evaluate()
if self.value == "*":
return self.children[0].evaluate() * self.children[1].evaluate()
if self.value == "/":
return self.children[0].evaluate() // self.children[1].evaluate()
class UnOp(Node):
def __init__(self, value, children):
super().__init__(value, children)
def evaluate(self):
if self.value == "+":
return self.children[0].evaluate()
if self.value == "-":
return -self.children[0].evaluate()
class NoOp(Node):
def __init__(self):
super().__init__(None, None)
def evaluate(self):
return None