前一篇文章中处理乘除法是利用往后多读一个符号,若为乘除号就计算出结果再继续往后读入;这里用栈实现,就是将读到的第一个符号压入符号栈,在读到下一个符号时,与栈顶的符号的优先级进行比较,若优先级比栈顶的那个符号低,就将栈顶符号的连接的两个数字(数字存在数字栈中)进行运算,否则将当前符号压入符号栈。遍历完一遍之后算式就只剩加减号了(或者直接得出答案了),然后就很简单了。至于括号的处理,和上一篇文章中的一样,在读入数字的时候,将括号内的内容视为整体用递归解决
#栈的结点
class Node(object):
def __init__(self, datas):
self.data = datas
self.next = None
#栈
class Stack(object):
def __init__(self):
self.top = None
def isEmpty(self):
if self.top == None:
return True
else:
return False
def push(self, data):
node = Node(data)
node.next = self.top
self.top = node
return self
def pop(self):
if self.isEmpty():
print("the stack is empty already")
return
else:
popData = self.top.data
self.top = self.top.next
return popData
#计算函数
def cal(exp):
#operator是符号栈
#operand是运算数栈
#loc是当前读取位置
#count用来匹配括号与括回
#operand1与operand2是两个运算数,存储operand中pop出的数字
#op是运算符,存储operator中pop出的符号
operator = Stack()
operand = Stack()
loc = 0
count = 0
while loc < len(exp):
if isOperator(exp[loc]):
if not operator.isEmpty():
while (not operator.isEmpty()) and priority(operator.top.data) >= priority(exp[loc]):
operand1 = operand.pop()
operand2 = operand.pop()
op = operator.pop()
operand.push(int(result(op, operand2, operand1)))
operator.push(exp[loc])
else:
firstOp = exp[loc]
if firstOp != "(":
firstOp = int(firstOp)
#处理括号
else:
locStart = loc + 1
count += 1 # 为了将( 与 ) 进行匹配
while count != 0:
loc += 1
if exp[loc] == "(":
count += 1
elif exp[loc] == ")":
count -= 1
locEnd = loc
firstOp = cal(exp[locStart:locEnd])
operand.push(firstOp)
loc += 1
while not operator.isEmpty():
operand1 = operand.pop()
operand2 = operand.pop()
op = operator.pop()
operand.push(int(result(op, operand2, operand1)))
evaluate = operand.pop()
return evaluate
return cal(x)