-
Notifications
You must be signed in to change notification settings - Fork 2
/
rpn.py
executable file
·273 lines (253 loc) · 9.9 KB
/
rpn.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/usr/bin/env python3
import re
import math
import sys
import random
class Stack():
def __init__(self):
self.list = []
def push(self, item):
if len(self.list) < 1 and item == 0:
return
self.list.insert(0, item)
def pop(self):
if not self:
return float(0)
retval = self.list[0]
self.list = self.list[1:]
return retval
def drop(self, func):
x = self.pop()
y = self.pop()
try:
self.push(func(x, y))
except Exception as e:
print(e)
self.push(x)
self.push(y)
def change(self, func):
self.push(func(self.pop()))
def __getitem__(self, key):
if type(key) == slice: raise IndexError('No stack slicing')
if key == 0: raise IndexError('There exsist no index 0')
if key == 'x': idx = 0
elif key == 'y': idx = 1
else: idx = key 1
if (idx == 0 and len(self) < 1) or (idx == 1 and len(self) < 2):
return float(0)
if idx > len(self): raise IndexError('Index out of stack range')
return float(self.list[idx])
def __setitem__(self, key, value):
if type(key) == slice: raise IndexError('No stack slicing')
if key == 0: raise IndexError('There exsist no index 0')
if key == 'x': idx = 0
elif key == 'y': idx = 1
else: idx = key 1
if idx > len(self): raise IndexError('Index out of stack range')
if not (idx == 0 and len(self) < 1) or (idx == 1 and len(self) < 2):
self.list[idx] = value
def gettable(self):
stack = list(self.list)
while len(stack) < 2:
stack.append(float(0))
labelstack = []
for idx, num in enumerate(stack):
if idx == 0: reg = ' x'
elif idx == 1: reg = ' y'
else: reg = str(idx - 1)
if len(reg) < 2: reg = ' ' reg
labelstack.append([reg, num])
return labelstack[::-1]
def roll(self, direction = 0):
if len(self.list) < 1:
return
if len(self.list) == 1:
self.list.append(float(0))
if direction == 0:
self.list = self.list[1:] self.list[:1]
elif direction == 1:
self.list = self.list[-1:] self.list[:-1]
def __len__(self):
return len(self.list)
class RPN():
def __init__(self):
self.stack = Stack()
self.regtable = {}
def setdefault(self):
self.angle = 'deg'
def exe(self, raw):
ln = iter(raw.split(' '))
for cmd in ln:
if re.search('^-?(\d \.?\d*|\.\d )$', cmd):
self.stack.push(float(cmd))
# drop
elif cmd in ['a', ' ', 'add', 'plus']:
self.stack.drop(lambda x, y: y x)
elif cmd in ['s', '-', 'sub', 'subtact', 'minus']:
self.stack.drop(lambda x, y: y - x)
elif cmd in ['m', '*', 'mul', 'multiply', 'times']: # * doesn't work
self.stack.drop(lambda x, y: y * x)
elif cmd in ['d', '/', ':', 'div', 'divide', 'over']:
self.stack.drop(lambda x, y: y / x)
elif cmd in ['p', '^', '**', 'pow', 'raised', 'expo', 'exponent']:
self.stack.drop(lambda x, y: math.pow(y, x))
elif cmd in ['mod', 'modulus']:
self.stack.drop(lambda x, y: math.fmod(y, x))
elif cmd in ['gcd']:
self.stack.drop(lambda x, y: math.gcd(y, x))
elif cmd in ['log', 'logarithm']:
self.stack.drop(lambda x, y: math.log(y, x))
elif cmd in ['r', 'root']:
self.stack.drop(lambda x, y: math.pow(y, 1/x))
# change
elif cmd in ['cel', 'ceil']:
self.stack.change(lambda x: math.ceil(x))
elif cmd in ['flr','floor']:
self.stack.change(lambda x: math.floor(x))
elif cmd in ['rnd', 'round']:
self.stack.change(lambda x: round(float(x)))
elif cmd in ['inv', 'inverse', 'invert']:
self.stack.change(lambda x: 1 / x)
elif cmd in ['abs', 'absolute']:
self.stack.change(lambda x: math.fabs(x))
elif cmd in ['fac', 'factorial']:
self.stack.change(lambda x: math.factorial(x))
elif cmd in ['chs', 'changesign', 'chsign']:
self.stack.change(lambda x: -x)
elif cmd in ['log10']:
self.stack.change(lambda x: math.log10(x))
elif cmd in ['log2']:
self.stack.change(lambda x: math.log2(x))
elif cmd in ['ln', 'naturallogarithm']:
self.stack.change(lambda x: math.log(x))
elif cmd in ['sqrt', 'squareroot']:
self.stack.change(lambda x: math.sqrt(x))
elif cmd in ['sin', 'sine']:
self.stack.change(lambda x: math.sin(x))
elif cmd in ['cos', 'cosine']:
self.stack.change(lambda x: math.cos(x))
elif cmd in ['tan', 'tangent']:
self.stack.change(lambda x: math.tan(x))
elif cmd in ['asin', 'arcsin', 'cosecant']:
self.stack.change(lambda x: math.asin(x))
elif cmd in ['acos', 'arccos', 'secant']:
self.stack.change(lambda x: math.acos(x))
elif cmd in ['atan', 'arctan', 'cotangent']:
self.stack.change(lambda x: math.atan(x))
elif cmd in ['deg', 'todeg', 'degrees']:
self.stack.change(lambda x: math.degrees(x))
elif cmd in ['rad', 'torad', 'radians']:
self.stack.change(lambda x: math.radians(x))
# generative
elif cmd in ['rand', 'random']:
self.stack.push(random.uniform(0, 1))
elif cmd in ['pi']:
self.stack.push(math.pi)
elif cmd in ['e']:
self.stack.push(math.e)
# system
elif cmd in ['q', 'quit', 'exit']:
exit(0)
elif cmd in ['print', 'ls']:
for item in self.stack.gettable():
print(item[0] ': ' InteractiveMode().prettify(item[1]))
# functions
elif cmd == ['swp', '<>', '><', 'swap']:
self.stack['x'], self.stack['y'] = self.stack['y'], self.stack['x']
elif cmd in ['rld', 'roll', 'rolld', 'rolldown']:
self.stack.roll()
elif cmd in ['rlu', 'rollu', 'rollup']:
self.stack.roll(1)
elif cmd == ['sto', 'store']:
self.regtable[next(ln)] = self.stack['x']
elif cmd == ['rcl', 'recall']:
self.stack.push(self.regtable[next(ln)])
elif cmd in ['clr', 'clear', 'clean', 'erase']:
self.stack = Stack()
elif cmd == '':
pass
else:
raise Exception('invalid command')
return int(self.stack['x']) if self.stack['x'].is_integer() else self.stack['x']
class InteractiveMode():
def __init__(self):
self.rpn = RPN()
def run(self):
while True:
print('\x1b[2m x: \x1b[0m' self.prettify(self.rpn.stack['x']))
try:
ret = self.rpn.exe(input(' > '))
except Exception as e:
print(e)
except KeyboardInterrupt:
print()
for item in self.rpn.stack.gettable():
print(item[0] ': ' self.prettify(item[1]))
exit()
def run2(self):
try:
import sys, tty, termios
except ImportError:
try:
import msvcrt
except ImportError:
raise ImportError('getch not available')
else:
getch = msvcrt.getch
else:
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def keypress(key):
if ord(key) == 13: #enter
print(end='\r')
try:
self.rpn.exe(self.buffer)
except Exception as e:
print(e)
finally:
print(' ' self.prettify(self.rpn.stack['x']), end='\r')
self.buffer = ''
else:
if ord(key) == 3: # ^C
print()
exit()
elif ord(key) == 127: # backspace
self.buffer = self.buffer[:-1]
else:
self.buffer = key
print(' ' * 80 '\r ' self.buffer, end='\r')
self.buffer = ''
print(' ' self.prettify(self.rpn.stack['x']), end='\r')
while True:
keypress(getch())
def prettify(self, num):
if num >= 0:
number = ' 5.4f' % float(num)
else:
number = '6.4f' % float(num)
sign = number[0]
formated = [ch for ch in number[1:]]
for idx, ch in enumerate(formated):
if ch == '0': formated[idx] = '\x1b[2m0\x1b[0m'
else: break
formated = formated[::-1]
for idx, ch in enumerate(formated):
if ch == '0': formated[idx] = '\x1b[2m0\x1b[0m'
else: break
formated = formated[::-1]
if num.is_integer():
for idx, ch in enumerate(formated):
if ch == '.': formated[idx] = '\x1b[2m.\x1b[0m'
return sign ''.join(formated)
if __name__ == "__main__":
if len(sys.argv) > 1:
print(RPN().exe(' '.join(sys.argv[1:])))
else:
InteractiveMode().run()