我正在用Python编写一个从中缀到后缀符号的转换器(当然,使用Shunting-Yard algorithm)。它似乎适用于以下情况:
>>>rpn('9+6-5')
96+5+
>>>rpn('(5+6)/5')
56+5/
>>>rpn('5+(6/5)')
565/+
但是,只要函数接收到以下表达式,它就会起作用(不返回):
^{pr2}$也就是说,除非有括号,否则当优先级较高的运算符位于优先级较低的运算符的右侧时,它不会返回。在
这是我使用的完整代码。它似乎很接近算法,但我可能错了。在
def defop(x):
return {'+': [2, 'left'], '-': [2, 'left'], '*': [3, 'left'], '/': [3, 'left'], '^': [4, 'right']}[x]
def rpn(exp):
stack, queue = [],[]
try:
if len(exp) > 0:
for token in list(exp):
if token in "+-*/^":
_o1 = defop(token)
while stack and stack[-1] in '+-*/&^':
_o2 = defop(stack[-1])
if _o1[1] == 'left' and _o1[0] <= _o2[0] or _o1[1] == 'right' and _o1[0] < _o2[0]:
queue.append(stack.pop())
stack.append(token)
elif token == '(':
stack.append(token)
elif token == ')':
for item in reversed(stack):
if item != '(':
queue.append(stack.pop())
else:
stack.pop()
break
else:
queue.append(token)
while stack:
if stack[-1] in '()':
return "Mismatched parentheses"
queue.append(stack.pop())
except:
return 'something borke'
return ''.join(queue)
当代码到达
while
循环并且if
语句中的表达式的计算结果为false时,代码中会发生什么情况?在将您链接到的维基百科文章中的重要部分加粗:
相关问题 更多 >
编程相关推荐