I'm trying to implement stack operations:
If I try to avoid .append() and use self.size for indexing and returning the size instead of using len(self.stack) it's throwing this:
Traceback (most recent call last):
File "C:\Users\user\Downloads\UPN.py", line 62, in <module>
print(round(test.upn(notation))
File "C:\Users\user\Downloads\UPN.py", line 50, in upn
self.push(float(el))
File "C:\Users\user\Downloads\UPN.py", line 16, in push
self.stack[self.size+1] = x
IndexError: list assignment index out of range
[]
Process finished with exit code 1
The codesnippet:
from time import sleep
class Stack:
def __init__(self):
self.stack = []
self.size = 0
self.operatoren = {
"+": (lambda a, b: a + b),
"-": (lambda a, b: a - b),
"*": (lambda a, b: a * b),
"/": (lambda a, b: a / b)
}
def push(self, x):
self.stack[self.size-1] = x
self.size += 1
def top(self):
return self.stack[self.size-1]
def pop(self):
self.size -= 1
return self.stack.pop()
def isEmpty(self):
return not self.stack
def size(self):
return self.size
def upn(self, expression):
elemente = expression.split()
for el in elemente:
print(self.stack)
if el not in self.operatoren:
self.push(float(el))
else:
zahl2 = self.pop()
zahl1 = self.pop()
ergebnis = self.operatoren[el](zahl1, zahl2)
self.push(ergebnis)
return self.pop()
test = Stack()
notation = "5.1 91 28 + 4.3 6 + * 777 + *"
print(round(test.upn(notation)))