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 *'))
If you run it in the above situation, the calculated value does not come out.
class '__main__.Stack'
That's what it says.
Which part should be modified to print the value
python
You can do it as below.
Compare to the code in the question.
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 *'))
849 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
563 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
562 Who developed the "avformat-59.dll" that comes with FFmpeg?
580 Uncaught (inpromise) Error on Electron: An object could not be cloned
586 GDB gets version error when attempting to debug with the Presense SDK (IDE)
© 2024 OneMinuteCode. All rights reserved.