파이썬 후위표기 계산기

조회수 1373회
class Stack:

    def __init__(self):
        self.list = list()

    def push(self, data):
        self.list.append(data)

    def pop(self):
        return self.list.pop()

class Calculator:

    def __init__(self):
        self.stack = Stack()

    def calculate(self, string):
        list = []
        for x in list:
            if x == '+':
                a = Stack.pop()
                b = Stack.pop()
                Stack.push(a + b)
            elif x == '-':
                a = Stack.pop()
                b = Stack.pop()
                Stack.push(a - b)
            elif x == '*':
                a = Stack.pop()
                b = Stack.pop()
                Stack.push(a * b)
            elif x == '/':
                a = Stack.pop()
                b = Stack.pop()
                Stack.push(a / b)
            else:
                Stack.push()
        return Stack


calc = Calculator()

print(calc.calculate('4 6 * 2 / 2 +'))

print(calc.calculate('2 5 + 3 * 6 - 5 *'))

위 상황에서 실행하면 계산한 값이 나오는게 아니라

class '__main__.Stack'

라고 출력이 됩니다.

값을 출력하기 위해서는 어느 부분을 수정해야 할까요

1 답변

  • 아래와 같이 하시면 됩니다.

    질문에 있는 코드와 비교해 보세요.

    class Stack:
    
        def __init__(self):
            self.list = list()
    
        def push(self, data):
            self.list.append(data)
    
        def pop(self):
            return self.list.pop()
    
    class Calculator:
    
        def __init__(self):
            self.stack = Stack()
    
        def calculate(self, string):
            list = string.split()
            for x in list:
                if x == '+':
                    b = self.stack.pop()
                    a = self.stack.pop()
                    self.stack.push(a + b)
                elif x == '-':
                    b = self.stack.pop()
                    a = self.stack.pop()
                    self.stack.push(a - b)
                elif x == '*':
                    b = self.stack.pop()
                    a = self.stack.pop()
                    self.stack.push(a * b)
                elif x == '/':
                    b = self.stack.pop()
                    a = self.stack.pop()
                    self.stack.push(a / b)
                else:
                    self.stack.push(float(x))
            return float(self.stack.pop())
    
    
    calc = Calculator()
    
    print(calc.calculate('4 6 * 2 / 2 +'))
    
    print(calc.calculate('2 5 + 3 * 6 - 5 *'))
    
    
    • 결과

    이미지

    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)