1.題目
Infix to Postfix
Write a function to convert a infix string into a postfix string. For this quiz, you may assume the string only contains numbers and the following operator: +, -, *, /, (, ).
將中綴表達式 ‘2-(5+3*2+1)/3’ 轉換成後綴表達式。
2.解題思路
從左到右掃描表達式:
(1)當前掃描到的是數字,直接添加到輸出字符穿out中;
(2)當前掃描到的是符號,將棧內所有與當前符號相同或相等優先級的符號出棧並添加到輸出字符串out中;再將當前符號入棧。
(3)當前掃描到的是 ‘(’ ,直接入棧;
(4)當前掃描到的是 ‘)’ ,一直出棧並把出棧的元素添加到輸出字符串out中直到遇到 ‘)’ ;再將 ‘(’ 出棧(注意:但千萬不要將 ‘(’ 添加到輸出字符串中了)。
(5)當表達式全部掃描完畢,將所有元素出棧並添加到輸出字符串out中。
3.code:
- 小技巧:用如下代碼防止表達式中混有空格。
infix = ‘’.join([c for c in infix if c != ’ '])
def infix_to_postfix(infix: str) -> str:
# Remove all white space
infix = ''.join([c for c in infix if c != ' '])
stk = []
out = ''
for c in infix:
if c.isdigit(): # if c is an operand
out += c
elif c == '(':
stk.append(c)
elif c == ')': # pop until '('
while stk[-1] != '(':
out += stk.pop()
stk.pop()
else: # if c is an operator
high_pre_op = '*/+-' if c in "+-" else '*/'
while stk and stk[-1] in high_pre_op:
out += stk.pop()
stk.append(c)
while stk:
out += stk.pop()
return out
# Call the above function
infix_to_postfix('2 +( 5 + 3 * 2 + 1 ) / 3')
result:
'2532*+1+3/+'