No need to jump through these loops, see 5.1.1 Using Lists as Stacks. Since appending to and popping from the end of a list are identical to pushing to or popping from the top of a stack, you can just use the list.append and list.pop methods to use a list as a stack.
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
Answer from Kimvais on Stack OverflowStack data structure in python - Stack Overflow
how to use the Stack()?
ELI5 Request: Data Structures - Stacks - Why would you need them? Are they better at memory management or something?
Day 12 of Learning Python DSA: Built Stack and Queue ...
I'm just wondering how I can use the Stack function alongside pop() and push() and peak() ? Is it a module that i have to import?
No need to jump through these loops, see 5.1.1 Using Lists as Stacks. Since appending to and popping from the end of a list are identical to pushing to or popping from the top of a stack, you can just use the list.append and list.pop methods to use a list as a stack.
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.