-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalc.py
More file actions
executable file
·77 lines (59 loc) · 1.79 KB
/
Copy pathcalc.py
File metadata and controls
executable file
·77 lines (59 loc) · 1.79 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/python
import sys
class Val(object):
val = None
def __init__(self, _val):
self.val = int(_val)
def eval(self):
return self.val
@staticmethod
def is_number(s):
try:
int(s)
return True
except ValueError:
pass
class Op(object):
op = None
# operator -> calculation , priority
oper = {
'*' : [lambda x,y : Val(x*y), 2],
'+' : [lambda x,y : Val(x+y),1],
'-' : [lambda x,y : Val(x-y),1],
'/' : [lambda x,y : Val(x/y),3],
}
def __init__(self, _op):
self.op = _op
# precedence
def isGreater(self, rhs):
return Op.oper[self.op][1] > Op.oper[rhs.op][1]
def eval(self, rhs, lhs):
print "eval op ",self.op
return Op.oper[self.op][0](rhs.eval(), lhs.eval())
class Expr(object):
@staticmethod
def eval(exprs):
print "eval ", exprs
lastLowestOp = None
lastLowestOpLocation = -1
if len(exprs) == 1:
token = exprs[0]
assert(Val.is_number(token))
return Val(token)
for i,token in enumerate(exprs):
print "token ",token
if token in Op.oper.keys():
op = Op(token)
if lastLowestOp is None:
lastLowestOp = op
lastLowestOpLocation = i
elif lastLowestOp.isGreater(op): # op < lastLowestOp
lastLowestOp = op
lastLowestOpLocation = i
assert(lastLowestOpLocation != -1)
lhs = Expr.eval(exprs[:lastLowestOpLocation])
rhs = Expr.eval(exprs[lastLowestOpLocation+1:])
return lastLowestOp.eval(lhs, rhs)
if __name__ == "__main__":
exprs = sys.argv[1];
print Expr.eval(exprs).eval()