有关用栈解决中缀转后缀表达式问题
from pythonds.basic.stack import Stackdef infixToPostfix(infixexp):
prec = {}
prec['*'] = 3
prec['/'] = 3
prec['+'] = 2
prec['-'] = 2
prec['('] = 1
opStack = Stack()
postfixlist = []
tokenlist = infixexp.split()
for token in tokenlist:
if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or '0123456789':
postfixlist.append(token)
elif token == '(':
opStack.push(token)
elif token in '*/+-':
while not opStack.isEmpty() and prec >= prec:
postfixlist.append(opStack.pop())
opStack.push(token)
elif token == ')':
while opStack.pop() != '(':
postfixlist.append(opStack.pop())
while not opStack.isEmpty():
postfixlist.append(opStack.pop())
return ''.join(postfixlist)
print(infixToPostfix("A * B + C * D"))
为什么得不到AB*CD*+呢 if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or '0123456789':
这句不符合python的思路 会短路 所有的都进这里了
应该改成
if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in '0123456789': lirenbing01 发表于 2020-11-23 15:55
对对,谢谢您~~
页:
[1]