First of all, in the Stack class, I need to initialize the stack to be empty.
class Stack:
def __init__(self):
"""
(Stack) -> NoneType
Initialize this Stack to be empty.
>>> isinstance(Stack(), Stack)True"""
self.data = []
And then, I can create a method called push which can put object x on top of the Stack.
def push(self, x):
"""
(Stack, object) -> NoneType
Place object x on top of this Stack.
"""
self.data.append(x)
Next, I can create a method called pop which can remove and return the top item in this Stack.
def pop(self):
"""
(Stack) -> object
Remove and return the top item from this Stack.
>>> s = Stack()
>>> s.push(1)
>>> s.push(5)
>>> s.pop()
5
"""
return self.data.pop()
Concluding two methods pop and push, it is easy to find this Stack is a last-in-first-out structure. Finally, I can create a method called is_empty to check whether the stack is empty.
def is_empty(self):
"""
(Stack) -> bool
Return whether this Stack is empty.
>>> s = Stack()
>>> s.push(1)
>>> s.push(5)
>>> s.pop()
5
>>> s.pop()
1
>>> s.is_empty()
True
"""
return self.data == []
Overall, if running this Stack, the object in this Stack will be put on the top of Stack and it is also removed out first. Therefore, it is an abstract data type with a last-in-first-out structure.