ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 1935. [Python]후위 표기식2
    Python_알고리즘/Silver III 2023. 5. 23. 02:26

    1. 문제

     

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

     

    1935번: 후위 표기식2

    첫째 줄에 피연산자의 개수(1 ≤ N ≤ 26) 가 주어진다. 그리고 둘째 줄에는 후위 표기식이 주어진다. (여기서 피연산자는 A~Z의 영대문자이며, A부터 순서대로 N개의 영대문자만이 사용되며, 길이

    www.acmicpc.net

     

    2. 접근 방법

     

    • 시간 제한: 2초
    • 메모리 제한: 128MB
    • 스택

     

    3. 파이썬 코드

     

    N = int(input())
    word = input()
    num_list = []
    for _ in range(N):
        num_list.append(int(input()))
    # 스택을 이용하여 값을 저장할 리스트
    stack = []
    # 딕셔너리를 통한 문자와 변수 매칭
    num_dict = {}
    # num_list 순회할 변수
    check = 0
    # 만약 i 값이 연산자인 경우 아닌 경우 나눠서 행동
    for i in word:
        # 연산자가 나온경우
        if i in ['+', '-', '*', '/']:
            # 뒤에서 2개의 피연산자를 뽑아서 사용
            A = stack.pop()
            B = stack.pop()
            # A,B가 각각 문자인 경우 A,B에 각각 딕셔너리의 value 값 반환
            if isinstance(A, str):
                A = num_dict[A]
            if isinstance(B, str):
                B = num_dict[B]
            # A,B가 문자가 아닌 경우 정수이므로 아래 계산식 수행
            if i == '+':
                stack.append(B + A)
            elif i == '-':
                stack.append(B - A)
            elif i == '*':
                stack.append(B * A)
            elif i == '/':
                stack.append(B / A)
        # 피연산자인 경우
        else:
            # 피연산자가 딕셔너리안에 없으면 딕셔너리에 연산자와 값을 추가
            if i not in num_dict:
                num_dict[i] = num_list[check]
                # 값을 추가했으니 num_list 를 순회할 변수 증가
                check += 1
            # stack 에 피연산자 추가
            stack.append(i)
    
    print("%.2f" % stack[0])

     

    • 틀렸던 코드
    더보기
    N = int(input())
    word = input()
    num_list = []
    for _ in range(N):
        num_list.append(int(input()))
    
    stack = []
    num_dict = {}
    check = 0
    
    for i in word:
        if i == "+":
            A = stack.pop()
            B = stack.pop()
            if isinstance(A,str) and isinstance(B,str):
                stack.append(num_dict[A]+num_dict[B])
            elif isinstance(A,str) and isinstance(B,int):
                stack.append(num_dict[A]+B)
            elif isinstance(A,int) and isinstance(B,str):
                stack.append(A+num_dict[B])
            else:
                stack.append(A+B)
        elif i == "*":
            A = stack.pop()
            B = stack.pop()
            if isinstance(A,str) and isinstance(B,str):
                stack.append(num_dict[A]*num_dict[B])
            elif isinstance(A,str) and isinstance(B,int):
                stack.append(num_dict[A]*B)
            elif isinstance(A,int) and isinstance(B,str):
                stack.append(A*num_dict[B])
            else:
                stack.append(A*B)
        elif i == "/":
            A = stack.pop()
            B = stack.pop()
            if isinstance(A,str) and isinstance(B,str):
                stack.append(num_dict[B]/num_dict[A])
            elif isinstance(A,str) and isinstance(B,int):
                stack.append(B/num_dict[A])
            elif isinstance(A,int) and isinstance(B,str):
                stack.append(num_dict[B]/A)
            else:
                stack.append(B/A)
        elif i == "-":
            A = stack.pop()
            B = stack.pop()
            if isinstance(A,str) and isinstance(B,str):
                stack.append(num_dict[B]-num_dict[A])
            elif isinstance(A,str) and isinstance(B,int):
                stack.append(B-num_dict[A])
            elif isinstance(A,int) and isinstance(B,str):
                stack.append(num_dict[B]-A)
            else:
                stack.append(B-A)
        else:
            if i not in num_dict:
                num_dict[i] = num_list[check]
                check += 1
            stack.append(i)
    print("%.2f" %stack[0])

     

     

    4. 문제를 풀고난 후 생각

     

    • 처음에 진행했던 코드는 내 생각에는 틀린점이 없다고 생각해서 이것저것 계속 수정해봤지만 TypeError 가 계속 해서 발생해서 Chat Gpt에 물어봤다 왜 오류가 발생하는지.
    • 그 이유로는 stack 이라는 리스트에 정수, 문자열 등 번갈아가면서 들어가기 때문에 이로인해 어느 테스트케이스에서 자꾸 TypeError가 걸렸던 것이다.
    • 이를 좀더 간단하게 바꿔서 각각 pop 한 값들이 str인경우 딕셔너리에서 값을 정수로 바꿔준 후 계산한 값을 stack에 넣어주고 꺼내쓰고 하는 방식으로 코드를 구현하였다.
    • 실수형 출력방식은 format 과 % 로 하는방식이 있었고 %방식을 사용했다.

     

    5. 문제를 푸는데 도움이 되는 지식

     

    • 스택

    'Python_알고리즘 > Silver III' 카테고리의 다른 글

    2012. [Python]등수 매기기  (0) 2023.05.24
    1735. [Python]분수 합  (0) 2023.05.23
    10974. [Python]모든 순열  (0) 2023.05.21
    1003. [Python]피보나치 함수  (0) 2023.05.19
    1431. [Python]시리얼 번호  (0) 2023.04.23

    댓글

Designed by Tistory.