-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnine.py
227 lines (180 loc) · 5.96 KB
/
nine.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
#!/usr/bin/env python
# nine.py - a postfix calculator for python 3 (python 2 support incoming)
# version 9-dev 2019-04-06
from __future__ import print_function, division
import readline, inspect, cmath, math, re
import sys
sys.setrecursionlimit(100)
def is_number(s):
try:
complex(s)
return True
except ValueError:
return False
def countFunctionArguments(func):
try:
return len(inspect.signature(func).parameters)
except:
return len(inspect.getargspec(func).args)
class Calculator:
def __init__(self):
self.operations = {
'+' : lambda a,b:a+b,
'-' : lambda a,b:b-a,
'/' : lambda a,b:b / a,
'*' : lambda a,b:a*b,
'**' : lambda a,b:b ** a,
'~': lambda a: a.inverse(),
'sin' : lambda a:a.trigfunc(cmath.sin),
'cosec' : lambda a:a.trigfunc(cmath.sin).inverse(),
'cos' : lambda a:a.trigfunc(cmath.cos),
'sec' : lambda a:a.trigfunc(cmath.cos).inverse(),
'tan' : lambda a:a.trigfunc(cmath.tan),
'cot' : lambda a:a.trigfunc(cmath.tan).inverse(),
'atan' : lambda a:a.trigfunc(cmath.atan),
'asin' : lambda a:a.trigfunc(cmath.asin),
'acos' : lambda a:a.trigfunc(cmath.acos),
'sqrt' : lambda a:a ** Symbol(self, 1/2.0),
'cbrt' : lambda a:a ** Symbol(self, 1/3.0),
'isqrt' : lambda a:(a ** Symbol(self, 1/2.0)).inverse(),
'icbrt' : lambda a:(a ** Symbol(self, 1/3.0)).inverse(),
'%' : lambda a,b:b.modulo(a),
'exp': lambda a:Symbol(self, math.e) ** a,
'ln' : lambda a:a.nat_log(),
'log' : lambda a,b:b.log(a),
'rad' : lambda a:a.trigfunc(lambda z: math.radians(z.real)),
'deg' : lambda a:a.trigfunc(lambda z: math.degrees(z.real)),
'arg' : lambda a:a.trigfunc(cmath.phase),
'abs' : lambda a:a.trigfunc( lambda z:math.hypot(z.real, z.imag) ),
'Re' : lambda a:Symbol(self, a.value.real),
'Im' : lambda a:Symbol(self, a.value.imag),
'=': lambda a,b:self.variableAssign(a,b)
}
self.stack = []
self.variables = {}
self.variables = {
Symbol(self, 'pi'): Symbol(self, math.pi),
Symbol(self, 'e'): Symbol(self, math.e),
Symbol(self, '\\'): Symbol(self, 0)
}
def execute(self, string):
'''
Execute a postfix string until no operations remain.
Assumes that operation arity conditions are already met,
and will raise errors if not.
The stack is cleared before execution begins.
After execution, the stack is assigned to the \ (backslash)
variable.
'''
# self.stack.clear()
del self.stack[:]
symbols = [Symbol(self, s) for s in string.split()]
search = next(
((index, sym) for index, sym in enumerate(symbols) \
if sym.type == Symbol.Operation), None)
while search:
index, oper = search
func = self.operations[oper.value]
args = countFunctionArguments(func)
popped = symbols[index-args:index][::-1]
result = func(*popped)
if result: symbols.insert(index+1, result)
del symbols[index-args:index+1]
search = next(
((index, sym) for index, sym in enumerate(symbols) \
if sym.type == Symbol.Operation), None)
self.stack += [sym if sym not in self.variables else self.variables[sym] for sym in symbols]
if len(self.stack) > 0: self.variableAssign(Symbol(self, '\\'), self.stack[-1])
def variableAssign(self, variableSymbol, value):
if value in self.variables:
value = self.variables[value]
self.variables[variableSymbol] = value
def __str__(self):
return str([i.value for i in self.stack])
class Symbol:
Types = ['number', 'dimension', 'variable', 'operation']
Number = Types[0]
Dimension = Types[1]
Variable = Types[2]
Operation = Types[3]
@property
def type(self):
return self._type
@type.setter
def type(self, newval):
if newval not in Symbol.Types:
raise ValueError('Invalid type: {}'.format(newval))
self._type = newval
@property
def value(self):
if self.type == Symbol.Variable:
# print(self)
# return self.calc.variables.get(self, Symbol(self.calc, 0))._value
if self in self.calc.variables:
return self.calc.variables[self].value
else:
return self._value
return self._value
def __init__(self, calc, value):
self.calc = calc
self._type = None
if is_number(value):
self._type = Symbol.Number
self._value = complex(value)
elif value in self.calc.operations:
self._type = Symbol.Operation
self._value = value
elif value.isalpha() or value == '\\':
self._type = Symbol.Variable
self._value = value
else:
raise ValueError('Failed to resolve Symbol type: {}'.format(value))
def __add__(self, other): return Symbol(self.calc, self.value + other.value)
def __sub__(self, other): return Symbol(self.calc, self.value - other.value)
def __mul__(self, other): return Symbol(self.calc, self.value * other.value)
def __truediv__(self, other): return Symbol(self.calc, self.value / other.value)
def __pow__(self, other): return Symbol(self.calc, self.value**other.value)
def trigfunc(self, func): return Symbol(self.calc, func(self.value))
def log(self, base): return Symbol(self.calc, cmath.log(self.value, base.value))
def nat_log(self): return Symbol(self.calc, cmath.log(self.value))
def inverse(self):
return Symbol(self.calc, 1.0 / self.value)
def pow(self, symbol):
return Symbol(self.calc, self.value ** symbol.value)
def __str__(self):
return 'Symbol({})'.format(self._value)
def __repr__(self):
return 'Symbol({}, {})'.format(self._value, self.type)
def __eq__(self, other):
# print('eq', self, other)
return other._value == self._value and other.type == self.type
def __hash__(self):
return hash(self._value)
if __name__ == '__main__':
c = Calculator()
try:
raw_input
except:
raw_input = input
while 1:
i = raw_input('> ')
c.execute(i)
print(c)
c.execute('4 6 + 2 / a = a a +')
# c.execute('4 6 +')
print(c.stack)
print(c.variables)
if 0:
x = Symbol(c, 10)
y = Symbol(c, 7)
result = x + y
print(result)
result = x - y
print(result)
result = x * y
print(result)
result = (x / y).inverse()
print(result)
x = Symbol(c, 2-2j)
y = Symbol(c, 5+1j)
print(y ** x)