Python rear-end calculator

Asked 2 years ago, Updated 2 years ago, 15 views

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

2022-09-20 18:01

1 Answers

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 *'))


2022-09-20 18:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.