May-12-2019, 08:07 PM
I was going to try and explain how you could go about doing it and point you in a direction.
Explaining would be hard work, so see the following code and ask questions about any of it that doesn't makes sense.
Using the operator module create a symbol dict.
Explaining would be hard work, so see the following code and ask questions about any of it that doesn't makes sense.
Using the operator module create a symbol dict.
import operator symbol_dict = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}Add the following method that makes use of the symbol dict
def calculate_stack(self): if self.is_empty(): return 0 items = self.get_stack() total = items[0] symbol = None for item in items[1:]: if symbol: total = symbol_dict[symbol](total, item) symbol = None elif item in ("+", "-", "*", "/"): symbol = item return totalFull code
import operator symbol_dict = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv} class stack(): def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def get_stack(self): return self.items def is_empty(self): return self.items == [] def is_full(self): return self.items == [1] def size(self): return len(self.items) def calculate_stack(self): if self.is_empty(): return 0 items = self.get_stack() total = items[0] symbol = None for item in items[1:]: if symbol: total = symbol_dict[symbol](total, item) symbol = None elif item in ("+", "-", "*", "/"): symbol = item return total s = stack() print("ar stack tuscias?") print(s.is_empty()) print("ar stack pilnas?") print(s.is_full()) s.push(9) s.push('+') s.push(5) s.push('+') s.push(8) s.push('+') s.push(7) s.push('+') s.push(3) print(s.size()) print(s.get_stack()) print(s.calculate_stack()) s2 = stack() s2.push(2) s2.push('*') s2.push(4) s2.push('-') s2.push(1) print(s2.calculate_stack())
Output:ar stack tuscias?
True
ar stack pilnas?
False
9
[9, '+', 5, '+', 8, '+', 7, '+', 3]
32
7