KY102 计算表达式
import sys
priority = {'+' : 0, "-" : 0, "*" : 1, "/" : 1}
def printEvaluation(line):
opStack, numStack = list(), list()
for c in line:
if c not in priority:
numStack.append(c)
else:
if len(opStack)==0:
opStack.append(c)
elif priority[opStack[-1]]>=priority[c]:
lastOp = opStack.pop()
b = numStack.pop()
a = numStack.pop()
res = str(eval(a+lastOp+b))
numStack.append(res)
if len(opStack)==0:
opStack.append(c)
elif priority[opStack[-1]]>=priority[c]:
lastOp = opStack.pop()
b = numStack.pop()
a = numStack.pop()
res = str(eval(a+lastOp+b))
numStack.append(res)
opStack.append(c)
else:
opStack.append(c)
else:
opStack.append(c)
while len(opStack)!=0:
lastOp = opStack.pop()
b = numStack.pop()
a = numStack.pop()
res = str(eval(a+lastOp+b))
numStack.append(res)
print(int(eval(numStack.pop())))
for line in sys.stdin:
line = line.strip()
ops = {"/","*","-","+"}
items = list()
start = 0
for i in range(len(line)):
if line[i] in ops:
items.append(line[start:i])
items.append(line[i])
start = i + 1
items.append(line[start:])
printEvaluation(items)
import sys
for line in sys.stdin:
line = line.strip()
print(int(eval(line)))