๊ฐœ๋ฐœ/๐Ÿค– ์•Œ๊ณ ๋ฆฌ์ฆ˜

[leetcode][Medium][Stack] 150. Evaluate Reverse Polish Notation ํ’€์ด, ํ•ด์„ค (python)

ttoance 2023. 11. 7. 23:11

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

 

Evaluate Reverse Polish Notation - LeetCode

Can you solve this real interview question? Evaluate Reverse Polish Notation - You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation [http://en.wikipedia.org/wiki/Reverse_Polish_notation]. Evaluate t

leetcode.com

 

1์ฐจ ํ’€์ด

class Solution(object):
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        
        stack = [] 
        for t in tokens:
            if t not in ['/', '+', '-', '*']:
                stack.append(t)
            else : 
                n1 = int(stack.pop())
                n2 = int(stack.pop())
                
                if t == '/':
                    check = math.trunc(float(n2) / float(n1))
                    stack.append(check)
                elif t == '+':
                    stack.append(n2+n1)
                elif t == '-':
                    stack.append(n2-n1)
                elif t == '*':
                    stack.append(n2*n1)
            # print(stack)
        
        return int(stack.pop())

 

 

ํ•ด์„ค

https://www.youtube.com/watch?v=iu0082c4HDE

 

 

stack = [] 
for c in tokens:
    if c == '+':
        stack.append(stack.pop() + stack.pop())
    elif c == '-':
        a, b = stack.pop(), stack.pop()
        stack.append(b - a)
    elif c == '*':
        stack.append(stack.pop() * stack.pop())
    elif c == '/':
        a, b = stack.pop(), stack.pop()
        stack.append(int(float(b) / a))
    else:
        stack.append(int(c))

return stack[0]

 

๋‚˜์™€ ๋‹ค๋ฅด๊ฒŒ ํ‘ผ ํ’€์ด๋Š” ๋‚˜๋ˆ—์…ˆ์ธ๋ฐ 

๋‚˜๋Š” check = math.trunc(float(n2) / float(n1)) ์ด๋ ‡๊ฒŒ ํ•ด์„œ ํ’€์—ˆ๋Š”๋ฐ, 

ํ•ด์„ค์—์„œ๋Š” stack.append(int(float(b) / a))๋กœ ์‰ฝ๊ฒŒ ํ’€์—ˆ๋‹ค. 

๋ฐ˜์‘ํ˜•