How to create generic stack in python?
My stack implementation in python:
class Node(object):
def __init__(self, d):
self.data = d
self.nextNode = None
class Stack(object):
def __init__(self):
self.top = None
def push(self, item):
newNode = Node(item)
newNode.nextNode = self.top
self.top = newNode
def pop(self):
if self.top == None:
return None
item = self.top.data
self.top = self.top.nextNode
return item
Now I am putting objects of class Node, but how implement generic Stack so that I can put there anything. For example, if I want create new type of nodes
class NodeWithMin:
def __init__(self, value, minval):
self.data = value
self.minval = minval
And be able create stack based on these type of nodes, so it should be something like this (of course it does not work):
class StackWithMin(qs.Stack):
def push(self, val):
if self.peek() != None:
minval = min(self.peek().value, val)
else:
minval = val
qs.Stack.push(NodeWithMinV2(val, minval))
any idea?
EDIT:
it did not work because I have next error:
unbound method push() must be called with Stack instance as first argument (got NodeWithMinV2 instance instead)
I missed self
You can just use a list, but I totally understand how you might want something better abstracted.
You can also use a deque, in the collections module. It can add or remove from either end, and is better abstracted than a list.
What you have looks good. If you want to put something with a minimum in it, just create a new class, and pass instances of it into your push method as the item argument.
I’m kind of guessing here, but if what you want is a priority queue, where you can pop the least valued node rather than just the thing at a given end by push chronology, you could check out the heapq module. It’s not terrifically abstracted either, but it works, and it’s fast, and there’s nothing to stop you from abstracting it better yourself.