-
Notifications
You must be signed in to change notification settings - Fork 0
/
formula_eval_function.py
62 lines (55 loc) · 1.84 KB
/
formula_eval_function.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
OPERATORS = {'+': (1, lambda x, y: x + y), '-': (1, lambda x, y: x - y),
'*': (2, lambda x, y: x * y), '/': (2, lambda x, y: x / y)}
def formula_eval(formula):
'''
https://habrahabr.ru/post/273253/
'''
def parse(formula_string):
formula_string = formula_string.replace(' ', '')
number = ''
for i, s in enumerate(formula_string):
if s in '1234567890.':
number += s
elif s == '-':
if i == 0 or formula_string[i-1] in '+-*/()':
number += s
elif number:
yield float(number)
number = ''
yield s
elif number:
yield float(number)
number = ''
if s in '+*/()':
yield s
if number:
yield float(number)
def shunting_yard(parsed_formula):
stack = []
for token in parsed_formula:
if token in OPERATORS:
while stack and stack[-1] != "(" and OPERATORS[token][0] <= OPERATORS[stack[-1]][0]:
yield stack.pop()
stack.append(token)
elif token == ")":
while stack:
x = stack.pop()
if x == "(":
break
yield x
elif token == "(":
stack.append(token)
else:
yield token
while stack:
yield stack.pop()
def calc(polish):
stack = []
for token in polish:
if token in OPERATORS:
y, x = stack.pop(), stack.pop()
stack.append(OPERATORS[token][1](x, y))
else:
stack.append(token)
return stack[0]
return calc(shunting_yard(parse(formula)))