0

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)))
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Pleb
  • 33
  • 7
  • The code in your error `self.stack[self.size+1] = x` doesn't match the code in your code `self.stack[self.size-1] = x`. Which is it? – Pranav Hosangadi May 03 '21 at 17:23
  • 1
    You can't just assign elements at any index you please if the list doesn't have that many elements in the first place. `.append()` is _the_ way to add elements to a list. – Pranav Hosangadi May 03 '21 at 17:23
  • Does this answer your question? [Why does this iterative list-growing code give IndexError: list assignment index out of range?](https://stackoverflow.com/questions/5653533/why-does-this-iterative-list-growing-code-give-indexerror-list-assignment-index) – Random Davis May 03 '21 at 17:27

1 Answers1

0

in class 'Stack':

class Stack:
    ...

    def push(self, x):
        self.stack[self.size-1] = x ##### target #####
        self.size += 1

    ...

in target line:

... self.size = 0 and self.stack[self.size-1] = x ->
... self.stack[0-1] = x
... self.stack[-1] = x

so self.stack[self.size] = x and:

class Stack:
    ...

    def push(self, x):
        self.stack[self.size] = x
        self.size += 1

    ...