I have 2 issues with the code below:
Should I throw an exception if pop() is invoked on an empty stack ?
class Stack(object): def __init__(self): self.storage = [] def isEmpty(self): return len(self.storage) == 0 def push(self,p): self.storage[:0] = p def pop(self): """issue: throw exception?""" return None
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop.
The basic Python data structures in Python include list, set, tuples, and dictionary. Each of the data structures is unique in its own way. Data structures are “containers” that organize and group data according to type.
The stack data structure is a linear data structure that accompanies a principle known as LIFO (Last In First Out) or FILO (First In Last Out). Real-life examples of a stack are a deck of cards, piles of books, piles of money, and many more.
deque to Create a Python Stack. The collections module contains deque , which is useful for creating Python stacks. deque is pronounced “deck” and stands for “double-ended queue.”
No need to jump through these loops, See 5.1.1 Using Lists as Stacks
If you insist on having methods isEmpty()
and push()
you can do:
class stack(list): def push(self, item): self.append(item) def isEmpty(self): return not self
You are right to use composition instead of inheritance, because inheritance brings methods in that you don't want to expose.
class Stack: def __init__(self): self.__storage = [] def isEmpty(self): return len(self.__storage) == 0 def push(self,p): self.__storage.append(p) def pop(self): return self.__storage.pop()
This way your interface works pretty much like list
(same behavior on pop
for example), except that you've locked it to ensure nobody messes with the internals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With