본문 바로가기
카테고리 없음

Leetcode 150. Reverse Polish Notation (Stack)

by Queen2 2022. 9. 22.
728x90
반응형

https://leetcode.com/problems/evaluate-reverse-polish-notation/

 

Evaluate Reverse Polish Notation - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Polish Notation이 궁금하신 분들은 아래 위키 백과를 참조하시길 바랍니다

 


 

Stack의 pop을 이용한 풀이)

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        f = []
        
        while tokens:
            for i in tokens:
                if i == "+":
                        n = f.pop()
                        m = f.pop()
                        f.append(int(n)+int(m))
                elif i == "-":
                        n = f.pop()
                        m= f.pop()
                        f.append(int(m)-int(n))
                elif i == "*":
                        n = f.pop()
                        m= f.pop()
                        f.append(int(n)*int(m))
                elif i == "/":
                        n = f.pop()
                        m = f.pop()
                        f.append(int(m)/int(n))
                else:
                        f.append(i)
                
            return int(f[0])

 

이 문제는 사실 stack을 이용해서 비교적 쉽게 풀었는데요, 코드가 깔끔하지 못하고 러닝타임이 길어서 다른 분들의

풀이를 간략하게 살펴봤습니다

 

 


 

Stack 심플 버전 ) 

class Solution(object):
    def evalRPN(self, tokens):
        stack = []
        for t in tokens:
            if t not in "+-*/":
                stack.append(int(t))
            else:
                r, l = stack.pop(), stack.pop()
                if t == "+":
                    stack.append(l+r)
                elif t == "-":
                    stack.append(l-r)
                elif t == "*":
                    stack.append(l*r)
                else:
                    stack.append(int(float(l)/r))
        return stack.pop()

 

이 코드에서 제일 흥미로웠던건 pop 기능을 저처럼 매번 반복한게 아니라, 아예 변수화 시켜서 간략하게 표현했습니다.

이런식으로 코드 구성이 가능한지 몰랐는데 새로 배워 갑니다!

 

 

Dict에 연산기능을 담은 Stack ) 

import operator

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        operators = {
            '+': operator.add,
            '-': operator.sub,
            '*': operator.mul,
            '/': lambda x, y: int(x / y),
        }
        stack = []
        for token in tokens:
            if token not in operators:
                stack.append(int(token))
                continue
            second, first = stack.pop(), stack.pop()
            stack.append(operators[token](first, second))

        return stack.pop()

 

이 방법을 보면서 이렇게도 생각할 수 있구나! 싶었는데요

연산자가 나오면 매칭되는 연산에 대한 인수를 각각 줘서 계산을 시킨다는 방법이 신기했네요

 

 


 

다른 사람들 코드를 보는건 역시 재밌고 신기한 일인 것 같아요 :))

728x90
반응형

댓글