-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpressionInterpreter.py
More file actions
482 lines (406 loc) · 19.6 KB
/
ExpressionInterpreter.py
File metadata and controls
482 lines (406 loc) · 19.6 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
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import re
from math import sqrt, cos, sin, tan, acos, asin, atan, log, exp, floor, pi
from random import random
class _Operator:
def __init__(self, key, precedence, nparams, func):
self.key = key
self.precedence = precedence
self.nparams = nparams
self.func = func
class ExpressionInterpreter:
"""Intérprete de expresiones con precedencia matemática, paréntesis y variables"""
def __init__(self, numeric_vars=None, string_vars=None, functions=None):
"""
Inicializa el intérprete con diccionarios de variables.
Args:
numeric_vars: Diccionario con variables numéricas {nombre: valor}
string_vars: Diccionario con variables de texto {nombre$: valor}
functions: Diccionario con definición de funciones {nombre[$]: FunctionDefinition}
"""
self._numeric_vars = numeric_vars if numeric_vars is not None else {}
self._string_vars = string_vars if string_vars is not None else {}
self._functions = functions if functions is not None else {}
self._register_operators((
_Operator('RND', 7, 0, lambda: random()),
_Operator('PI', 7, 0, lambda: pi),
_Operator('FN', 7, 2, lambda n, p: self._functions[n].resolve(self, p)),
_Operator('NEG', 6, 1, lambda a: -a),
_Operator('SQR', 6, 1, lambda a: sqrt(a)),
_Operator('COS', 6, 1, lambda a: cos(a)),
_Operator('SIN', 6, 1, lambda a: sin(a)),
_Operator('TAN', 6, 1, lambda a: tan(a)),
_Operator('ACS', 6, 1, lambda a: acos(a)),
_Operator('ASN', 6, 1, lambda a: asin(a)),
_Operator('ATN', 6, 1, lambda a: atan(a)),
_Operator('LN', 6, 1, lambda a: log(a)),
_Operator('EXP', 6, 1, lambda a: exp(a)),
_Operator('INT', 6, 1, lambda a: floor(a)),
_Operator('ABS', 6, 1, lambda a: abs(a)),
_Operator('STR$', 6, 1, lambda a: str(f"{a:g}") if isinstance(a, (int, float)) else (_ for _ in ()).throw(ValueError(f"'{a}' is not a number"))),
_Operator('LEN', 6, 1, lambda a: len(a) if isinstance(a, str) else (_ for _ in ()).throw(ValueError(f"{a} is not a string"))),
_Operator('SGN', 6, 1, lambda a: -1 if a < 0 else 1 if a > 0 else 0),
_Operator('VAL', 6, 1, lambda a: self.evaluate(a)),
_Operator('^', 5, 2, lambda a, b: a ** b),
_Operator('*', 5, 2, lambda a, b: a * b),
_Operator('/', 5, 2, lambda a, b: a / b if b != 0 else (_ for _ in ()).throw(ValueError("Zero division"))),
_Operator('+', 4, 2, lambda a, b: a + b),
_Operator('-', 4, 2, lambda a, b: a - b),
_Operator('AT', 3, 2, lambda f, c: f"\x1b[{f};{c}f"),
_Operator('TAB', 3, 1, lambda c: f"\x1b[{c}G"),
_Operator('TO', 3, 3, lambda s, a, b: s[a-1:b] if isinstance(s, str) else (_ for _ in()).throw(ValueError(f"{s} is not a string"))),
_Operator('START_TO', 3, 2, lambda s, b: s[:b] if isinstance(s, str) else (_ for _ in()).throw(ValueError(f"{s} is not a string"))),
_Operator('TO_END', 3, 2, lambda s, a: s[a-1:] if isinstance(s, str) else (_ for _ in()).throw(ValueError(f"{s} is not a string"))),
_Operator('>', 2, 2, lambda a, b: a > b),
_Operator('<', 2, 2, lambda a, b: a < b),
_Operator('=', 2, 2, lambda a, b: a == b),
_Operator('<=', 2, 2, lambda a, b: a <= b),
_Operator('=<', 2, 2, lambda a, b: a <= b),
_Operator('>=', 2, 2, lambda a, b: a >= b),
_Operator('=>', 2, 2, lambda a, b: a >= b),
_Operator('<>', 2, 2, lambda a, b: a != b),
_Operator('NOT', 1, 1, lambda a: not a),
_Operator('AND', 0, 2, lambda a, b: a and b),
_Operator('OR', 0, 2, lambda a, b: a or b),
_Operator('NOR', 0, 2, lambda a, b: not (a or b))
))
def _register_operators(self, operators):
self._operators = {}
for operator in operators:
self._operators[operator.key] = operator
def _tokenize(self, expr):
"""Convierte la expresión en tokens"""
expr = expr.strip()
self._tokens = []
self._expr_index = 0
while self._expr_index < len(expr):
# Saltar espacios
if expr[self._expr_index].isspace():
self._expr_index += 1
continue
# String entre comillas
if expr[self._expr_index] == '"':
j = self._expr_index + 1
while j < len(expr) and (expr[j] != '"' or (j+1 < len(expr) and expr[j+1] == '"')):
j += 1
if expr[j-1] == '"' and j < len(expr) and expr[j] == '"':
j += 1
if j >= len(expr):
raise ValueError("String sin cerrar")
self._tokens.append(('STRING', expr[self._expr_index+1:j].replace('""','"')))
self._expr_index = j + 1
# Operador
elif self._is_operator(expr):
pass
# Variable o número
elif expr[self._expr_index].isalpha():
# Variable (empieza con letra)
j = self._expr_index
while j < len(expr) and (expr[j].isalnum() or expr[j] == '$'):
j += 1
var_name = expr[self._expr_index:j]
# Buscar índices
indices = None
while j < len(expr) and (expr[j] == " "):
j += 1
if j < len(expr) and expr[j] == "(":
start_indices = j + 1
while j < len(expr) and expr[j] != ")":
j += 1
if j < len(expr) and expr[j] == ")":
end_indices = j
else:
raise ValueError(f"Bad index for array '{var_name}'")
if not "TO" in expr[start_indices:end_indices]:
tokens_temp = self._tokens
self._tokens = []
indices = [self.evaluate(index) for index in expr[start_indices:end_indices].split(",")]
self._tokens = tokens_temp
j += 1
else:
j = start_indices - 1
# Determinar si es variable de string o numérica
if var_name.endswith('$'):
if var_name not in self._string_vars:
raise ValueError(f"Variable de texto '{var_name}' no definida")
if not indices:
self._tokens.append(('STRING', self._string_vars[var_name]))
else:
item = self._string_vars[var_name]
for index in indices:
item = item[index-1]
if isinstance(item, list):
item = "".join(item)
self._tokens.append(('STRING', item))
else:
if var_name not in self._numeric_vars:
raise ValueError(f"Variable numérica '{var_name}' no definida")
self._tokens.append(('NUMBER', self._numeric_vars[var_name]))
self._expr_index = j
# Número
elif expr[self._expr_index].isdigit():
j = self._expr_index
# Si es un signo negativo, avanzar
if expr[self._expr_index] == '-':
j += 1
# Leer el número
while j < len(expr) and (expr[j].isdigit() or expr[j] == '.'):
j += 1
num_str = expr[self._expr_index:j]
if '.' in num_str:
self._tokens.append(('NUMBER', float(num_str)))
else:
self._tokens.append(('NUMBER', int(num_str)))
self._expr_index = j
# Paréntesis
elif expr[self._expr_index] == '(':
self._tokens.append(('PAREN_OPEN', expr[self._expr_index]))
self._expr_index += 1
elif expr[self._expr_index] == ')':
if self._tokens[-1][1] == 'TO':
self._tokens[-1] = ('OPERATOR' ,'TO_END')
self._tokens.append(('PAREN_CLOSE', expr[self._expr_index]))
self._expr_index += 1
elif (expr[self._expr_index] == ','
and self._tokens[0][1] == 'AT'):
self._expr_index += 1
else:
raise ValueError(f"Carácter inválido: {expr[self._expr_index]}")
def _is_operator(self, expression):
if expression[self._expr_index] == '-' and (len(self._tokens) == 0 or self._tokens[-1][0] == "PAREN_OPEN"):
self._tokens.append(('OPERATOR', 'NEG'))
self._expr_index += 1
return True
operator_candidate = ""
for operator in self._operators:
end_index = self._expr_index + len(operator)
if (expression[self._expr_index: end_index] == operator
and len(operator_candidate) < len(operator)):
operator_candidate = operator
if operator_candidate:
self._expr_index += len(operator_candidate)
if operator_candidate == "TO" and self._tokens[-1][0] == "PAREN_OPEN":
operator_candidate = "START_TO"
self._tokens.append(('OPERATOR', operator_candidate))
if operator_candidate == "FN":
while expression[self._expr_index] == ' ':
self._expr_index += 1
name_start = self._expr_index
while expression[self._expr_index] not in ' (':
self._expr_index += 1
name_end = self._expr_index
self._tokens.append(('FUNCTION_NAME', expression[name_start: name_end]))
while expression[self._expr_index] != '(':
self._expr_index += 1
params_start = self._expr_index + 1
while expression[self._expr_index] != ')':
self._expr_index += 1
params_end = self._expr_index
self._expr_index += 1
self._tokens.append(('FUNCTION_PARAMS', expression[params_start: params_end]))
return True
return False
def evaluate(self, expr):
"""Evalúa la expresión usando el algoritmo Shunting Yard"""
self._tokenize(expr)
return self._evaluate_tokens()
def _evaluate_tokens(self):
"""Evalúa los tokens usando notación postfija (RPN)"""
output_queue = []
operator_stack = []
for token_type, token_value in self._tokens:
if token_type in ('NUMBER', 'STRING', 'FUNCTION_NAME', 'FUNCTION_PARAMS'):
output_queue.append(token_value)
elif token_type == 'OPERATOR':
while (operator_stack
and operator_stack[-1] != '('
and ((self._operators[operator_stack[-1]].precedence
> self._operators[token_value].precedence)
or ( self._operators[token_value].nparams == 2
and self._operators[operator_stack[-1]].precedence
== self._operators[token_value].precedence))):
op = operator_stack.pop()
self._apply_operator(output_queue, op)
operator_stack.append(token_value)
elif token_type.startswith('PAREN'):
if token_value == '(':
operator_stack.append('(')
else: # ')'
while operator_stack and operator_stack[-1] != '(':
self._apply_operator(output_queue, operator_stack.pop())
if not operator_stack:
raise ValueError("Paréntesis desbalanceados")
operator_stack.pop() # Remover '('
# Aplicar operadores restantes
while operator_stack:
op = operator_stack.pop()
if op == '(':
raise ValueError("Paréntesis desbalanceados")
self._apply_operator(output_queue, op)
if len(output_queue) != 1:
raise ValueError("Expresión inválida")
return output_queue[0]
def _apply_operator(self, stack, operator):
"""Aplica un operador a los últimos dos elementos del stack"""
nparams = self._operators[operator].nparams
if len(stack) < nparams:
raise ValueError(f"Operación no válida: {operator}")
if nparams == 2:
right = stack.pop()
left = stack.pop()
if operator == 'FN' or operator in '<>>=<=':
result = self._operators[operator].func(left, right)
stack.append(result)
# Operaciones con números
elif isinstance(left, (int, float)) and isinstance(right, (int, float)):
result = self._operators[operator].func(left, right)
stack.append(result)
# Operaciones con strings
elif isinstance(left, str) and isinstance(right, str):
if operator == '+':
stack.append(left + right)
else:
raise ValueError(f"Operación {operator} no válida entre strings")
elif isinstance(left, str) and isinstance(right, (int, float)):
if operator == '*':
stack.append(left * int(right))
elif operator == 'START_TO':
end = int(right)
string = left
result = self._operators[operator].func(string, end)
stack.append(result)
elif operator == 'TO_END':
start = int(right)
string = left
result = self._operators[operator].func(string, start)
stack.append(result)
else:
raise ValueError(f"Operación {operator} no válida entre string y número")
elif isinstance(left, (int, float)) and isinstance(right, str):
if operator == '*':
stack.append(right * int(left))
else:
raise ValueError(f"Operación {operator} no válida entre número y string")
else:
raise ValueError("Operación no válida")
elif nparams == 1:
result = self._operators[operator].func(stack.pop())
stack.append(result)
elif nparams == 0:
result = self._operators[operator].func()
stack.append(result)
elif nparams == 3:
if operator == 'TO':
end = int(stack.pop())
start = int(stack.pop())
string = stack.pop()
result = self._operators[operator].func(string, start, end)
stack.append(result)
# Ejemplos de uso
if __name__ == "__main__":
# Definir diccionarios de variables
numeric_vars = {
'x': 10,
'y': 5,
'pi': 3.14159,
'edad': 25,
'precio': 99.99
}
string_vars = {
'nombre$': 'Juan',
'apellido$': 'Pérez',
'saludo$': 'Hola',
'lenguaje$': 'Python'
}
# Crear intérprete con las variables
interpreter = ExpressionInterpreter(numeric_vars, string_vars)
test_cases = [
# Pruebas con números negativos
('-2', -2), # -2
('-5 + 3', -2), # -5 + 3 = -2
('10 + (-5)', 5), # 10 + (-5) = 5
('(-2) * 3', -6), # -2 * 3 = -6
('-10 / 2', -5.0), # -10 / 2 = -5.0
('5 - (-3)', 8), # 5 - (-3) = 8
# Operaciones con variables numéricas
('x + y', 15), # 10 + 5 = 15
('x * 2', 20), # 10 * 2 = 20
('(x + y) * 2', 30), # (10 + 5) * 2 = 30
('precio - 10', 89.99), # 99.99 - 10 = 89.99
('pi * 2', 6.28318), # 3.14159 * 2 = 6.28318
# Operaciones con variables de texto
('saludo$ + " " + nombre$', "Hola Juan"), # "Hola Juan"
('lenguaje$ * 3', "PythonPythonPython"), # "PythonPythonPython"
('nombre$ + " " + apellido$', "Juan Pérez"),# "Juan Pérez"
# Mezcla de variables y literales
('x + 5', 15), # 10 + 5 = 15
('(x + y) / 3', 5.0), # 15 / 3 = 5.0
# Expresiones complejas
('(x * 2) + (y * 3)', 35), # 20 + 15 = 35
('saludo$ + ", " + nombre$ + "!"', "Hola, Juan!"), # "Hola, Juan!"
# Más pruebas con negativos
('(-5 + 3) * 2', -4), # (-5 + 3) * 2 = -4
('x + (-y)', 5), # 10 + (-5) = 5
('x + (-3)', 7), # 10 + (-3) = 7
# Booleans
('x < y', False),
('x > y', True),
('x >= 10 AND y = 5', True),
('x = 10 OR y < 5', True),
('x = 0 NOR y = 0', True),
('x < 6', False),
('NOT x < 6', True),
('NOT x < 6 AND NOT y = 7', True),
('nombre$ = "Juan"', True),
('nombre$ = "Pepe"', False),
#Math functions
('SQR 4 + 5', 7),
('SQR (4 + 5)', 3),
('SQR (-4 + 13)', 3),
('ABS (-3)', 3),
('SGN (-3)', -1),
('SGN 3', 1),
('SGN 0', 0),
#String functions
('"Esto es una cadena"', 'Esto es una cadena'),
('"""Esto"" es una cadena"', '"Esto" es una cadena'),
('"Hola """', 'Hola "'),
('STR$ (10*10)', "100"),
('LEN STR$ 100.000', 3),
('VAL "2*3"', 6),
('VAL ("2" + "*3")', 6),
('VAL "VAL ""VAL """"2"""""""', 2),
('"Esto es una cadena"(1 TO 4)', 'Esto'),
('"Esto es una cadena"(TO 4)', 'Esto'),
('"Esto es una cadena"(13 TO 18)', 'cadena'),
('"Esto es una cadena"(6+7 TO 6*3)', 'cadena'),
('"Esto es una cadena"(13 TO)', 'cadena'),
('"Esto es una cadena"(y TO x)', ' es un'),
('lenguaje$(2 TO 5)', 'ytho')
]
print("Variables numéricas:", numeric_vars)
print("Variables de texto:", string_vars)
print("\n" + "=" * 60)
print("Evaluando expresiones con variables:")
print("=" * 60)
for expr, expected_result in test_cases:
try:
result = interpreter.evaluate(expr)
correct_message = "OK" if expected_result == result else f"; expected: {expected_result}"
print(f"{expr:35} = {result} {correct_message}")
except Exception as e:
print(f"{expr:35} = ERROR: {e}")
# Ejemplo interactivo
print("\n" + "=" * 60)
print("Prueba tus propias expresiones (escribe 'salir' para terminar):")
print("Puedes usar las variables definidas arriba")
print("=" * 60)
while True:
try:
expr = input("\nExpresión: ").strip()
if expr.lower() in ('salir', 'exit', 'quit'):
break
if expr:
result = interpreter.evaluate(expr)
print(f"Resultado: {result}")
except Exception as e:
print(f"Error: {e}")