파이썬 후위표기 계산기
조회수 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 *'))
- 결과
-
(•́ ✖ •̀)
알 수 없는 사용자
댓글 입력