輸入一個中序運算式,運算元為整數,運算子包含加減乘除和括號,將該運算式轉成後序運算式。
def infix_to_postfix(expression):
#運算子優先級
precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '(': 0}
stack = [] #存放運算子
output = [] #最終結果
i = 0
while i < len(expression):
token = expression[i]
#如果是數字,放入輸出
if token.isdigit():
num = token
while i + 1 < len(expression) and expression[i + 1].isdigit():
i += 1
num += expression[i]
output.append(num)
#遇到左括號,放入堆疊
elif token == '(':
stack.append(token)
#遇到右括號,則將堆疊中左括號前面的運算子全部pop出來
elif token == ')':
while stack and stack[-1] != '(':
output.append(stack.pop())
stack.pop() #移除左括號
#依優先級處理運算子
else:
while stack and precedence[stack[-1]] >= precedence[token]:
output.append(stack.pop())
stack.append(token)
i += 1
#將剩下的運算子pop
while stack:
output.append(stack.pop())
return ' '.join(output)
#輸入輸出
expression = input("")
postfix_expression = infix_to_postfix(expression)
print(postfix_expression)
input:
135-256/4(3-2)
output:
135 25 6 * 4 / 3 2 - * -