-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEasyCalculator.py
385 lines (340 loc) · 13.2 KB
/
EasyCalculator.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import PySimpleGUI as sg
import re
import math
# Put multiplications in parentesis and roots
def innerMult(sentence):
innerMultRegex = re.compile(r'[^+-/*√\^](\(|√)|(\)|!)[^+-/*√\^]')
mo = innerMultRegex.search(sentence)
try:
mo = mo.group()
if mo in '(√':
sentence = innerMultRegex.sub(f'{mo[:-1]}*{mo[-1]}', sentence)
else:
sentence = innerMultRegex.sub(f'{mo[0]}*{mo[1:]}', sentence)
print(mo)
print(sentence)
except AttributeError:
return ''
return sentence
# Verify if there's only a negative number on the sentence
def isnegative(sentence):
try:
negativeRegex = re.compile(fr'^-\d*[.]?\d*$')
mo = negativeRegex.search(sentence)
mo.group()
except AttributeError:
return False
return True
# Replace duplicate signs
def signreplace(sentence):
if '--' in sentence:
sentence = sentence.replace('--', '+')
if '++' in sentence:
sentence = sentence.replace('++', '+')
if '+-' in sentence:
sentence = sentence.replace('+-', '-')
if '-+' in sentence:
sentence = sentence.replace('-+', '-')
return sentence
# Find the desired operation with regex
def findregex(operator, sentence):
regex1 = re.compile(fr'-?\d*(\.\d*)?\{operator}')
regex2 = re.compile(fr'\{operator}\d*(\.\d*)?')
mo = regex1.search(sentence)
part1 = mo.group()[:len(mo.group())-1]
mo = regex2.search(sentence[1:])
part2 = mo.group()[1:]
return [part1, part2, part1 + operator + part2]
# Verify if the sentence isn't illegal
def validatesentence(sentence):
if sentence.count('(') != sentence.count(')'):
sentence = 'Syntax Error!'
return sentence
# Computes all operations on the sentence
def operations(sentence):
while '!' in sentence:
factorialRegex = re.compile(r'\d\.?\d?!')
mo = factorialRegex.search(sentence)
factorial = mo.group()
factorial = factorial.replace('!', '')
print(factorial)
fact = math.factorial(int(factorial))
sentence = sentence.replace(str(factorial) + '!', str(fact))
print(sentence)
while '^' in sentence or '√' in sentence:
if '^' in sentence and ('√' not in sentence or sentence.index('^') < sentence.index('√')):
regex = findregex('^', sentence)
power1 = regex[0]
power2 = regex[1]
power = float(power1) ** float(power2)
if power == int(power):
power = int(power)
sentence = sentence.split(regex[2])
sentence = str(power).join(sentence)
print(sentence)
else:
sqrtRegex = re.compile(r'√\d*')
mo = sqrtRegex.search(sentence)
square = mo.group()
root = math.sqrt(float(square[1:]))
if root == int(root):
root = int(root)
sentence = sentence.replace(square, str(root))
while '*' in sentence or '/' in sentence:
if '*' in sentence and ('/' not in sentence or sentence.index('*') < sentence.index('/')):
ponto = 0
regex = findregex('*', sentence)
if '.' in regex[0]:
ponto += len(regex[0][regex[0].index('.')+1:])
regex[0] = regex[0][:regex[0].index('.')] + regex[0][regex[0].index('.')+1:]
mult1 = regex[0]
if '.' in regex[1]:
ponto += len(regex[1][regex[1].index('.')+1:])
regex[1] = regex[1][:regex[1].index('.')] + regex[1][regex[1].index('.')+1:]
mult2 = regex[1]
mult = float(mult1) * float(mult2) / (10**ponto)
if mult == int(mult):
mult = int(mult)
sentence = sentence.split(regex[2])
sentence = str(mult).join(sentence)
else:
ponto = 0
regex = findregex('/', sentence)
print(regex)
if '.' in regex[0]:
ponto += len(regex[0][regex[0].index('.')+1:])
regex[0] = regex[0][:regex[0].index('.')] + regex[0][regex[0].index('.')+1:]
div1 = regex[0]
if '.' in regex[1]:
ponto -= len(regex[1][regex[1].index('.')+1:])
regex[1] = regex[1][:regex[1].index('.')] + regex[1][regex[1].index('.')+1:]
div2 = regex[1]
div = float(div1) / float(div2) / (10**ponto)
if div == int(div):
div = int(div)
sentence = sentence.split(regex[2])
sentence = str(div).join(sentence)
print(sentence)
while '+' in sentence or ('-' in sentence and not isnegative(sentence)):
if isnegative(sentence):
break
if '+' in sentence and ('-' not in sentence[1:] or sentence.index('+') < sentence[1:].index('-')):
regex = findregex('+', sentence)
su1 = regex[0]
su2 = regex[1]
su = float(su1) + float(su2)
if su == int(su):
su = int(su)
sentence = sentence.split(regex[2])
sentence = str(su).join(sentence)
else:
regex = findregex('-', sentence)
print(regex)
sub1 = regex[0]
sub2 = regex[1]
print(regex[2])
sub = float(sub1) - float(sub2)
if sub == int(sub):
sub = int(sub)
sentence = sentence.split(regex[2])
sentence = str(sub).join(sentence)
print(sentence)
return sentence
# Separates the sentence's blocks and computes each one in the right order
def calculator(sentence):
parRegex = re.compile(r'\(.*\)')
sentence = signreplace(sentence)
while innerMult(sentence) != '':
sentence = innerMult(sentence)
print(sentence)
while '(' in sentence and ')' in sentence:
sentence2 = sentence
while '(' in sentence2 and ')' in sentence2:
mo = parRegex.search(sentence2)
par = mo.group()
sentence2 = par[1:len(par)-1]
print(sentence2)
result = operations(sentence2)
sentence = sentence.split('(' + sentence2 + ')')
sentence = result.join(sentence)
sentence = operations(sentence)
return sentence
sg.theme('DarkGreen3')
layout = [
[sg.Text('EasyCalculator ', justification='r', size=(23, 1), font='Arial 18')],
[sg.Text(size=(300, 1), key='num2', justification='r')],
[sg.Text('0', size=(300, 3), justification='r', key='display')],
[sg.Button('MS', key='memoryStore', size=(5, 2), ), sg.Button('MR', key='memoryRestore', size=(5, 2)),
sg.Button('M+', key='memorySum', size=(5, 2)), sg.Button('M-', key='memorySub', size=(5, 2)),
sg.Button('C', key='clear', size=(5, 2))],
[sg.Button('sen', key='sin', size=(5, 2)), sg.Button('cos', key='cos', size=(5, 2)),
sg.Button('tan', key='tan', size=(5, 2)), sg.Button('x²', key='potwo', size=(5, 2)),
sg.Button('√x', key='squareRoot', size=(5, 2))],
[sg.Button('π', key='pi', size=(5, 2)), sg.Button('(', key='par1', size=(5, 2)),
sg.Button(')', key='par2', size=(5, 2)), sg.Button('x!', key='factorial', size=(5, 2)),
sg.Button('/', key='div', size=(5, 2))],
[sg.Button('x^y', key='potx', size=(5, 2)), sg.Button('7', key='seven', size=(5, 2)),
sg.Button('8', key='eight', size=(5, 2)), sg.Button('9', key='nine', size=(5, 2)),
sg.Button('X', key='mult', size=(5, 2))],
[sg.Button('10^x', key='tenPot', size=(5, 2)), sg.Button('4', key='four', size=(5, 2)),
sg.Button('5', key='five', size=(5, 2)), sg.Button('6', key='six', size=(5, 2)),
sg.Button('-', key='minus', size=(5, 2))],
[sg.Button('|x|', key='modelX', size=(5, 2)), sg.Button('1', key='one', size=(5, 2)),
sg.Button('2', key='two', size=(5, 2)), sg.Button('3', key='three', size=(5, 2)),
sg.Button('+', key='plus', size=(5, 2))],
[sg.Button('log', key='log', size=(5, 2)), sg.Button('+/-', key='inverter', size=(5, 2)),
sg.Button('0', key='zero', size=(5, 2)), sg.Button('.', key='point', size=(5, 2)),
sg.Button('=', key='equal', size=(5, 2))]
]
calculatorGUI = sg.Window('EasyCalculator', layout, size=(385, 460))
sentence = ''
memory = 0
while True:
events, values = calculatorGUI.read()
if events == 'clear':
sentence = ''
elif events == 'memoryStore':
memory = float(sentence)
elif events == 'memoryRestore':
if not str(memory).isdecimal():
memory = int(memory)
sentence += str(memory)
elif events == 'memorySum':
memory += float(memory)
elif events == 'memorySub':
memory -= float(memory)
elif events == 'zero':
sentence += '0'
elif events == 'one':
sentence += '1'
elif events == 'two':
sentence += '2'
elif events == 'three':
sentence += '3'
elif events == 'four':
sentence += '4'
elif events == 'five':
sentence += '5'
elif events == 'six':
sentence += '6'
elif events == 'seven':
sentence += '7'
elif events == 'eight':
sentence += '8'
elif events == 'nine':
sentence += '9'
elif events == 'plus':
if not sentence == '':
if sentence[-1].isnumeric():
sentence += '+'
elif sentence[-1] in '-*/^√':
sentence = sentence[0:-1]
sentence += '+'
elif events == 'minus':
if not sentence == '':
if sentence[-1].isnumeric() or sentence[-1] in '*/^':
sentence += '-'
elif sentence[-1] in '+√':
sentence = sentence[0:-1]
sentence += '-'
else:
sentence += '-'
elif events == 'mult':
if not sentence == '':
if sentence[-1].isnumeric():
sentence += '*'
elif sentence[-1] in '+-/^√':
sentence = sentence[0:-1]
sentence += '*'
elif events == 'div':
if not sentence == '':
if sentence[-1].isnumeric():
sentence += '/'
elif sentence[-1] in '+*-^√':
sentence = sentence[0:-1]
sentence += '/'
elif events == 'potx':
if sentence[-1].isnumeric():
sentence += '^'
elif sentence[-1] in '+*-/√':
sentence = sentence[0:-1]
sentence += '^'
elif events == 'squareRoot':
if sentence[-1].isnumeric():
sentence += '√'
elif sentence[-1] in '+*-/':
sentence = sentence[0:-1]
sentence += '√'
elif events == 'factorial':
if sentence[-1].isnumeric():
sentence += '!'
elif events == 'par1':
sentence += '('
elif events == 'par2':
sentence += ')'
elif events == 'point':
dotRegex = re.compile(r'\d*\.?\d*$')
mo = dotRegex.search(sentence)
if '.' not in mo.group():
sentence += '.'
elif events == 'tenPot':
operationRegex = re.compile(r'[+-/*]\d*')
operate = operationRegex.findall(sentence)
if not operate:
sentence = '10^' + sentence
else:
operate = ''.join(operate[-1])
newOperation = operate
newOperation = newOperation.replace(newOperation[1:], '10^'+newOperation[1:])
sentence = sentence.replace(operate, newOperation)
elif events == 'log':
if sentence.isnumeric():
sentence = round(math.log10(float(sentence)), 5)
sentence = str(sentence)
elif events == 'sin':
if sentence.isnumeric():
sentence = round(math.sin(math.radians(float(sentence))), 3)
if '.' not in str(sentence):
int(sentence)
sentence = str(sentence)
elif events == 'cos':
if sentence.isnumeric():
sentence = round(math.cos(math.radians(float(sentence))), 3)
if '.' not in str(sentence):
int(sentence)
sentence = str(sentence)
elif events == 'tan':
if sentence.isnumeric():
sentence = round(math.tan(math.radians(float(sentence))), 3)
if '.' not in str(sentence):
int(sentence)
sentence = str(sentence)
elif events == 'potwo':
sentence += '^2'
elif events == 'pi':
sentence += '3.1415926535897932384626433832795'
elif events == 'inverter':
sentence = validatesentence(sentence)
if sentence != 'Syntax Error!':
sentence = calculator(sentence)
if sentence != '0' and sentence != 'Syntax Error!' and sentence != '':
if '-' in sentence:
sentence = sentence.replace('-', '')
else:
sentence = '-' + sentence
elif events == 'modelX':
sentence = validatesentence(sentence)
if sentence != 'Syntax Error!':
sentence = calculator(sentence)
if '-' in sentence:
sentence = sentence.replace('-', '')
elif events == 'equal':
sentence = validatesentence(sentence)
if sentence != 'Syntax Error!':
sentence = calculator(sentence)
elif events == sg.WINDOW_CLOSED:
break
if sentence == '':
calculatorGUI['display'].update('0')
continue
calculatorGUI['display'].update(sentence)