The easiest way to create Stack that I found was this:
self.stack = 
raise Exception("nothing to pop")
raise Exception("Nothing to peek")
return len(self.stack) == 0
for x in self.stack.reverse(): #Reverse list, so when printing last pushed value is first and the oldest is printed last.
What it does is when creating Stack Variable:
- it makes new list called
- When you push something to Stack, it is added at the end of list.
- When you pop something from Stack, it is taken away form list (method
pop() will not only return value from list, but also delete it)
- When you peek something from Stack, it returns last value on list without deleting it.
- When you want to check size of stack, it measures list size.
- When you want to use
__str__ you print all variables from list.
I have reversed the list using
for x in stack:. This was done because otherwise
x would be equivalent to
stack in first run,
stack in second etc. However we must not forget that
stack is the oldest value placed in stack, and the newest is the value with the highest index in list. Reversing the list allows to print from the newest value to the oldest.
A little bit more of explanation:
self.stack.pop(len(self.stack)-1) - This code will pop last value from list. It contains
-1 because length of stack is started from 1 while indexing is started from 0. Function
len() returns (in this case) length of list
if self.isEmpty(): raise Exception("Nothing to peek") - This code will run its function
isEmpty() from its own class, which returns Boolean value (which is perfect for our if statement).
self.stack[len(self.stack)-1] while using list you will use list name (in this case stack) and then index you want to access, e.g. stack (will return second value in list, dont forget about 0-indexing).