-
Notifications
You must be signed in to change notification settings - Fork 0
/
p27.py
55 lines (50 loc) · 1.54 KB
/
p27.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
51
52
53
54
55
class Number:
def __init__(self, x):
self.value = x
def __repr__(self):
return "%s" % self.value
def reducible(self):
return False
class Complex:
def __init__(self, l, r):
self.left = l
self.right = r
def __repr__(self):
return "%s * %s" % (self.left, self.right)
def reducible(self):
return False
class Add:
def __init__(self, l, r):
self.left = l
self.right = r
def __repr__(self):
return "%s + %s" % (self.left, self.right)
def reducible(self):
return True
def reduce(self):
if self.left.reducible():
return Add(self.left.reduce(), self.right)
elif self.right.reducible():
return Add(self.left, self.right.reduce())
else:
return Number(self.left.value + self.right.value)
class Multiply:
def __init__(self, l, r):
self.left = l
self.right = r
def __repr__(self):
return "%s * %s" % (self.left, self.right)
def reducible(self):
return True
def reduce(self):
if self.left.reducible():
return Add(self.left.reduce(), self.right)
elif self.right.reducible():
return Add(self.left, self.right.reduce())
else:
return Number(self.left.value * self.right.value)
#expression = Add(Multiply(Number(1), Number(2)), Multiply(Number(3), Number(4)))
#expression.reducible()
#expression.reduce()
#expression.reduce().reduce()
#expression.reduce().reduce().reduce()