一次失败的小尝试,利用栈来完成中缀表达式的计算 ,能力有限,写到后面逻辑就完全乱了,因此有很多问题。最后返回来看发现当时写的又多又乱,有很大问题,但也不太想改了。
对于表达式的输入,仅限于字符串,格式也有要求,每个字符之间都要有空格,并且需要用“()”来说明运算的顺序
代码如下,以后有时间会来完善,改正错误
class Stack:
def __init__(self):
self.List=[]
def push(self,item):
self.List.append(item)
def pop(self):
return self.List.pop()
def isEmpty(self):
return self.List==[]
def peek(self):
return self.List[-1]
def size(self):
return len(self.List)
def calculate(a,b,c):
if b=='+':
return a+c
elif b=='*':
return a*c
elif b=='-':
return c-a
elif b=='/':
return c/a
def InfixtoPstfix(infix):
Dict={}
Dict['+']=1
Dict['-']=1
Dict['*']=2
Dict['/']=2
Dict['(']=3
Dict[')']=3
index=0
infixList=infix.split()
numStack=Stack()#数字栈
opStack=Stack()#操作栈
while index <= len(infixList)-1:
if infixList[index] not in Dict and infixList[index] != ')':
numStack.push(int(infixList[index]))
elif infixList[index] == '(':#Push
opStack.push(infixList[index])
elif infixList[index] == ')':
while not opStack.isEmpty() and opStack.peek() in '+-*/':
numStack.push(calculate(numStack.pop(),opStack.pop(),numStack.pop()))
if opStack.pop() == '(':
while not opStack.isEmpty() and opStack.peek() in '+-*/':
numStack.push(calculate(numStack.pop(),opStack.pop(),numStack.pop()))
opStack.push(infixList[index])
elif opStack.isEmpty() or Dict[infixList[index]] > Dict[opStack.peek()] :#Push
opStack.push(infixList[index])
elif Dict[infixList[index]] <= Dict[opStack.peek()]:
while not opStack.isEmpty() and opStack.peek() in '+-*/':
numStack.push(calculate(numStack.pop(),opStack.pop(),numStack.pop()))
opStack.push(infixList[index])
index =index + 1
if opStack.isEmpty():
return numStack.pop()
elif not opStack.isEmpty():
while not opStack.isEmpty() and opStack.peek() in '+-*/':
numStack.push(calculate(numStack.pop(),opStack.pop(),numStack.pop()))
return numStack.pop()
#举个例子,输入的格式需要很标准,不然计算不准确
a = '( 1 + ( 2 * ( 6 - 3 ) ) * 5 ) - 10 )'
b = InfixtoPstfix(a)
print('计算:',a)
print('计算结果', b)
运行结果如下:
计算: ( 1 + ( 2 * ( 6 - 3 ) ) * 5 ) - 10 )
计算结果 21
结果还是正确的,但是去掉多余的括号,结果就会变成
计算: 1 + 2 * ( 6 - 3 ) * 5 - 10
计算结果 25
未完待续,有时间会来改正