I'm an absolute beginner with Python and generally not very good at coding yet, so hopefully my code isn't too laughable :D
I need to write a Stack Program, where the Stack & the Stack Program is a list. This is my code:
class Stack:
def __init__(self):
self.items = []
def pop(self):
return self.items.pop()
def push(self, item):
self.items.append(item)
def isEmpty(self):
return self.items == []
def execute(list):
result = Stack()
for x in list:
if 'LOAD' in x:
number = substring_after(x, " ")
result.push(number)
elif 'ADD' in x:
result = result.pop() + result.pop()
elif 'MUL' in x:
result = result.pop() * result.pop()
elif 'SUB' in x:
first = result.pop()
result = result.pop() - first
elif 'DIV' in x:
first = result.pop()
result = result.pop() / first
elif 'PRINT' in x:
print(result.pop())
if result.isEmpty():
print('Execution completed')
else:
print('There are still values in the Stack')
else:
print('Not a valid statement for Stack Program')
def substring_after(s, delim):
return s.partition(delim)[2]
def main():
operation1 = ["LOAD 2", "LOAD 3", "ADD", "LOAD 4", "MUL", "PRINT"]
operation2 = ["LOAD 4", "LOAD 5", "ADD", "LOAD 2", "LOAD 3", "ADD",
"MUL", "PRINT"]
operation3 = ["LOAD 6", "LOAD 7", "LOAD 4", "SUB", "DIV", "LOAD 5",
"MUL", "PRINT"]
execute(operation1)
if __name__ == '__main__':
main()
The error I'm getting is:
Traceback (most recent call last):
File "XXX/EA2-Stack.py", line 53, in <module> main()
File "XXX/EA2-Stack.py", line 47, in main execute(operation1)
File "XXX/EA2-Stack.py", line 19, in execute result.push(number)
AttributeError: 'str' object has no attribute 'push'
I don't understand:
1.) Why does it say, that there is no 'push'? I defined a method called 'push'. I also tried to write: push(result, number), but then it says "unresolved reference"
2.) Why does it say Attribute push? It's not an attribute, it's a method.
I've got the feeling, that I'm missing something here :( Thanks for helping me :>