Problem overview
A stack is a pile where you only touch the top. The last value you put in is the first one you take out, which is called LIFO, last in, first out, like a pile of plates. You build a class MyStack that keeps whole numbers in a Python list, self._data, and offers four methods:
push(self, value)puts a value on top and returns nothing.pop(self)removes the top value and returns it.peek(self)returns the top value and leaves it on the stack.size(self)returns how many values are on the stack.
The driver pushes 10, 20 and 30, looks at the top (30), reads the size (3), pops 30, pops 20 and 10, shows that the size is 0, pushes 7 and checks the top and size again.
Approach: the end of the list is the top
A Python list is already a good stack, as long as you work at one end. Appending to the end and removing from the end are cheap, and the last element is always the value pushed most recently. So the top of the stack is the end of the list. Working at the start of the list instead would force every other element to shift.
Each method then wraps a single list operation: append for push, the list's own pop() for pop, index -1 for peek and len for size. The class adds a clear vocabulary on top of the list and a leading underscore in _data that says "internal, use the methods". The underscore is a convention, and Python doesn't enforce it.
Every stack gets its own list, because self._data = [] runs inside __init__ each time a stack is created. Two stacks never share their contents.
Step by step
- Declare the class
MyStack. A class body can't be empty, so the next step gives it a line. - Add the constructor,
__init__(self). It runs once, when the driver writesMyStack(). - Create the storage: an empty list in
self._data. A new stack holds nothing, so its size is 0. - Add
push(self, value), at the same indentation as__init__. - Append
valueto the end ofself._data. The end is the top. - Add
pop(self), which takes onlyself. - Return the list's own
pop(). That single call removes the last item and hands it back, which is exactly what a stack'spoppromises. - Add
peek(self), a method that looks without taking. - Return
self._data[-1]. The index-1means the last item, and reading by index removes nothing. - Add
size(self). - Return
len(self._data). One value per list item, so the length is the size.
The solution in Python
class MyStack:
def __init__(self):
self._data = []
def push(self, value):
self._data.append(value)
def pop(self):
return self._data.pop()
def peek(self):
return self._data[-1]
def size(self):
return len(self._data)
s = MyStack()
s.push(10)
s.push(20)
s.push(30)
print("Top: " + str(s.peek()))
print("Size: " + str(s.size()))
print("Pop: " + str(s.pop()))
print("Size: " + str(s.size()))
print("Pop: " + str(s.pop()))
print("Pop: " + str(s.pop()))
print("Empty size: " + str(s.size()))
s.push(7)
print("Top: " + str(s.peek()))
print("Size: " + str(s.size()))
Two methods share a name with a list method, but they are different things. MyStack.pop is the method you wrote. Inside it, self._data.pop() calls the list's method, so there is no clash.
What the driver prints
Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1
Pushing 10, 20, 30 puts 30 on top. peek reports it without removing anything, so the size stays 3. Each pop then returns the newest remaining value: 30, 20, 10. When the stack is empty, size() is 0, and the stack still works: after push(7) the top is 7 and the size is 1.
Complexity
Every method is O(1). Appending to a list is amortized constant time (an occasional append has to grow the list's storage, but averaged over many pushes the cost per push stays constant). Removing the last item, reading [-1] and calling len don't depend on how many values the stack holds. The stack uses O(n) space for n values.
Edge cases and common mistakes
- An empty stack. The lesson's tests never call
poporpeekon an empty stack. With this solution,pop()raisesIndexError: pop from empty listandpeek()raisesIndexError: list index out of range. - Reusing a stack after it empties. Nothing special is needed: pushing again simply starts filling the list again.
peekthat removes. Usingself._data.pop()inpeekwould return the right value but shrink the stack. After twopeekcalls on a stack holding 1 and 2, the size must still be 2.- Working at the front.
insert(0, value)andpop(0)also give LIFO if used together, but they shift every element, so they are the slow way to build a stack. - Forgetting
self.. A baredata = []in the constructor is a local variable that is gone when the constructor returns, and the other methods can't see it. - A shared list. Writing the list at class level, outside
__init__, would give every stack the same list. Creating it in the constructor keeps each stack separate. - Printing instead of returning.
pop,peekandsizereturn their answers. The driver does the printing.
Testing
- Push 1 and 2, then call
peek()twice andsize(): the top is 2 both times and the size is 2. - Push 5 on one stack and leave another untouched: their sizes are 1 and 0.
- Push 3, 1, 4 on top of a 5 and pop until
size()reaches 0: the values come out as[4, 1, 3, 5], the reverse of the pushing order. - Call
pop()on a new stack:IndexError.
