Achieve a simple four operations

'' '
Simple non-parenthetical negative four operations

Note:
1. do not add =
2. Enter the equation must be right

Test case:
(111+ (30-12) /2.5) * 11-114.34
'' '

operators = ['+', '-', '*', '/', '(', ')']
priority = {'+': 1, '-': 1, '*': 2, '/': 2}

change_to DEF (S):
Print (F 'original formula: {S}')
RES = List () # reverse Polish notation
op = list () # store operator
i = 0 # subscript
while i <len (s) :
# numbers directly into RES
IF S [I]> = '0' and S [I] <= '. 9':
NUM = ""
the while I <len (S) and ((S [I]> = '0 'and S [I] <='. 9 ') or S [I] ==' '):.
NUM = S + [I]
I = +. 1
res.append (the eval (NUM)) # really convenient to the eval function
S elif [I] in Operators:
IF S [I] == '(':
op.append (S [I])
# op element taken right parenthesis encountered placed RES
elif S [I] == ')' :
the while OP:
TEMP = op.pop ()
IF TEMP == '(':
BREAK
the else:
res.append (TEMP)
the else:
if len (on) == 0:
op.append (s [i]),
i = 1 +
Continue
the while op:
TEMP = op.pop ()
# priority determination, if the priority was put op (when taken out first extraction)
IF TEMP == '(' priority or [S [I]]> priority [TEMP] :
op = + [TEMP, S [I]]
BREAK
the else:
res.append (TEMP)
IF Not op:
op.append (S [I])
I =. 1 +
# op added excess
the while op:
res.append (op.pop ())
return RES

def calculation(res):
stack = list()
for i in res:
if i in operators:
nums1 = stack.pop()
nums2 = stack.pop()
if i == '+':
stack.append(nums2 + nums1)
if i == '-':
stack.append(nums2 - nums1)
if i == '':
stack.append(nums2
nums1)
if i == '/':
stack.append(nums2 / nums1)
else:
stack.append(i)
return stack.pop()

RUN DEF ():
the while True:
S = INPUT ( "input to the calculation formula: \ n-")
IF == S 'Q':
BREAK
RES = change_to (List (s.replace does ( "", "")))
Print ( f "is converted to the reverse Polish notation: \ n-RES {}")
ANS = calculation (RES)
Print ( "calculation results:% s"% ans)

if name == 'main':
run()

Guess you like

Origin www.cnblogs.com/fanwenkeer/p/11711463.html