algorithm/problem solving

acmicpc.net 1918(스택,후위표기식), 1935(스택,후위표기식)

qkqhxla1 2016. 11. 20. 16:53

https://www.acmicpc.net/problem/1918


후위표기식으로 만들자.

# -*- encoding: cp949 -*-
s=raw_input()
stack = []
answer = ''
for c in s:
    if c.isalpha():
        answer += c
    else:
        if len(stack)==0:
            stack.append(c)
        else:
            while stack:
                if stack[-1] in ['*','/'] and c not in ['(',')']:
                    answer += stack.pop()
                elif stack[-1] in ['+','-'] and c in ['+','-']:
                    answer += stack.pop()
                else:
                    break
            if c!=')':
                stack.append(c)
            if c==')':
                while True:
                    p = stack.pop()
                    if p=='(': break
                    answer += p

while stack:
    answer += stack.pop()
print answer

https://www.acmicpc.net/problem/1935


깔끔하게 짜지못함. 뭔가 맘에안드는 코드.....

# -*- encoding: cp949 -*-
n=input()
s=raw_input()
d = dict([[chr(i+65),raw_input()+'.0'] for i in xrange(n)])
stack = []
cnt = 0
while not s.isdigit():
    flag = True
    for i in xrange(len(s)):
        if s[i] in ['+','-','*','/']:
            answer = str(eval(d[s[i-2]]+s[i]+d[s[i-1]])) 
            d[chr(97+cnt)] = answer
            s = s[:i-2] + chr(97+cnt) + s[i+1:]
            cnt += 1
            flag = False
            break
    if flag: break
print '{:.2f}'.format(float(d[s]))