-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpnpp.py
executable file
·143 lines (119 loc) · 3.63 KB
/
rpnpp.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#!/usr/bin/env python3
import math
import os
import sys
DEBUG = False
if os.environ.get("RPNPP_DEBUG") == "1":
DEBUG = True
elif "-d" in sys.argv:
DEBUG = True
# Notazione polacca inversa con assegnazione variabili
OPERATIONS = {
# arithmetic
"+": [lambda x, y : x + y, float, float],
"-": [lambda x, y : x - y, float, float],
"*": [lambda x, y : x * y, float, float],
"/": [lambda x, y : x / y, float, float],
"**": [lambda x, y : x ** y, float, float],
"sin": [lambda x : math.sin(x), float],
"cos": [lambda x : math.cos(x), float],
"tan": [lambda x : math.tan(x), float],
# logical
"<": [lambda x, y: x < y, float, float],
">": [lambda x, y: x > y, float, float],
"<=": [lambda x, y: x <= y, float, float],
">=": [lambda x, y: x >= y, float, float],
"==": [lambda x, y: x == y, float, float],
# condition
"if": [lambda x, y, cond: x if cond else y, None, None, bool],
}
def read_row():
try:
value = input()
return value
except EOFError:
return None
def try_float(value):
try:
return float(value)
except:
return None
def try_bool(value):
if value.lower() == "true":
return True
if value.lower() == "false":
return False
def handleOperation(stack, opName, op):
# op[0]: lambda
# len(op) - 1: # of arguments
# op[1..len(op)-1]: arguments
if len(stack) < len(op) - 1:
print(f" [EE] Stack does not contain enough arguments for OP: \"{opName}\"")
return False
args = []
for i in range(1, len(op)):
arg = stack.pop()
if op[-i] is None or type(arg) is op[-i]:
args.insert(0, arg) # last removed item is the first argument
else:
isError = True
print(f" [EE] Type mismatch: expected \"{op[i]}\" but type({arg}) == \"{type(arg)}\"")
return False
if DEBUG:
print(f" [DD] Executing OP: {args} \"{opName}\"")
result = op[0](*args)
stack.append(result)
return True
def handleVariables(stack, variables, value):
if value[0] == '$':
# variable substitution
num = variables.get(value[1:])
if num is None:
print(f" [EE] Variable not found: {value}")
return False
stack.append(num)
elif len(stack) > 0:
# variable assignment
variables[value] = stack.pop()
else:
print(f" [EE] Empty stack while trying to fetch an item to be assigned to VAR: \"{value}\"")
return False
return True
def main():
isError = False
stack = []
variables = {}
while not isError:
row = read_row()
if row is None:
break
for value in row.split():
num = try_float(value)
if num is not None:
stack.append(num)
continue
num = try_bool(value)
if num is not None:
stack.append(num)
continue
op = OPERATIONS.get(value)
if op is not None:
# operation
if not handleOperation(stack, value, op):
isError = True
break
else:
# variables
if not handleVariables(stack, variables, value):
isError = True
break
if DEBUG:
print(f" [DD] Stack: {stack}")
if len(stack) == 1:
print(stack[0])
return not isError
print(stack)
return False
if __name__ == "__main__":
if not main():
exit(1)