#an exception to be raised by an empty stack class EmptyStack(Exception): pass class Stack: def __init__(self): self._items = [] #non-public list for storing stack elements def __len__(self): return len(self._items) def isEmpty(self): return len(self) == 0 def push(self, e): self._items.append(e) #add the element at the end of the list def top(self): if self.isEmpty(): raise EmptyStack("Stack Is Empty.") return self._items[-1] #Return the last element in list def pop(self): if self.isEmpty(): raise EmptyStack("Stack Is Empty.") return self._items.pop() #pop the last item from the list # test the stack S = Stack() S.push("A") S.push("B") S.push("C") print(S.pop()) print(S.pop()) print(S.pop()) print(S.pop())
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter