Skip to content
本站總訪問量
本站訪客數 人次

後序運算式

輸入 中序 輸出 後序

青年程式設計競賽 2016 2.py

python
# 題目 2:後序(Postfix)轉換問題 (10%) (中序轉後序)
st = input()
level = {'+': 1, '-': 1, '*': 2, '/': 2}

output = []
stack = []

for char in st:
    if char.isalnum():
        output.append(char)
    elif char in '+-*/':

        while (stack and (stack[-1] in '+-*/') and (level[stack[-1]] >= level[char])):
            output.append(stack.pop())
        stack.append(char)

    elif char == '(':
        stack.append(char)
    elif char == ')':  # 遇到括號
        while stack and stack[-1] != '(':
            output.append(stack.pop())
        stack.pop()
    print(stack,output)

while stack:
    output.append(stack.pop())

print(''.join(output))

輸入 後序 輸出 結果

zerojudge f698. 後序運算式

python
data = list(input().split())
stack = []
while data:
    num_or_op = data.pop(0)
    try:    #int
        eval(num_or_op)
        stack.append(num_or_op)
    except: #op
        b = stack.pop()
        a = stack.pop()
        stack.append(str(eval(a+num_or_op+b)))
print(f'{float(stack[0]):.0f}')

106 正試 H 後序運算式

python
for _ in range(int(input())):
    line = input().split()
    stack = []

    for i in line:
        if i.isdigit():
            stack.append(i)
        else:
            stack.append(int(eval(f'{stack.pop()}{i}{stack.pop()}')))
    print(stack[0])

Contributors

The avatar of contributor named as lucashsu95 lucashsu95

Changelog