|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
from pythonds.basic import Stack
import string
def hanshu(n):
dict1 = {}
dict1["*"] = 3
dict1["/"] = 3
dict1["+"] = 2
dict1["-"] = 2
dict1["("] = 1
opstack = Stack()
poslist = []
tokenlist = n.split()
for token in tokenlist:
if token in string.ascii_uppercase:
poslist.append(token)
elif token == "(":
opstack.push(token)
elif token == ")":
toptoken = opstack.pop()
while toptoken != "(":
poslist.append(toptoken)
toptoken = opstack.pop()
else:
while not (opstack.isEmpty()) and dict1[opstack.peek()] >= dict1[token]:
poslist.append(opstack.pop())
opstack.push(token)
while not opstack.isEmpty():
poslist.append(opstack.pop())
return "".join(poslist)
print(hanshu('( ( A + B ) * D ) * N'))
这是中序表达式变为后续表达式的代码
有哪位大神能解释一下为什么会想出这样的代码,有什么依据吗 |
|