-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
54 lines (46 loc) · 1.55 KB
/
lambda_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
import re
def lambda_handler (event, context):
return {
#'calculation' : eval(event) Did not choose to go with eval so there's better security on Server side
'calculation' : evaluate(event)
}
def is_number(str):
try:
int(str)
return True
except ValueError:
return False
def peek(stack):
return stack[-1] if stack else None
def apply_operator(operators, values):
operator = operators.pop()
right = values.pop()
left = values.pop()
values.append(eval("{0}{1}{2}".format(left, operator, right)))
def greater_precedence(op1, op2):
precedences = {'+' : 0, '-' : 0, '*' : 1, '/' : 1}
return precedences[op1] > precedences[op2]
def evaluate(expression):
tokens = re.findall("[+/*()-]|\d+", expression)
values = []
operators = []
for token in tokens:
if is_number(token):
values.append(int(token))
elif token == '(':
operators.append(token)
elif token == ')':
top = peek(operators)
while top is not None and top != '(':
apply_operator(operators, values)
top = peek(operators)
operators.pop()
else:
top = peek(operators)
while top is not None and top not in "()" and greater_precedence(top, token):
apply_operator(operators, values)
top = peek(operators)
operators.append(token)
while peek(operators) is not None:
apply_operator(operators, values)
return values[0]