implementing stack in python code example
Example 1: best python stack implementation
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
Example 2: stack data structure python
#using doubly linked list
from collections import deque
myStack = deque()
myStack.append('a')
myStack.append('b')
myStack.append('c')
myStack
deque(['a', 'b', 'c'])
myStack.pop()
'c'
myStack.pop()
'b'
myStack.pop()
'a'
myStack.pop()
#Traceback (most recent call last):
#File "<console>", line 1, in <module>
##IndexError: pop from an empty deque
Example 3: def dft(self, array): stack = Stack() visited = set() stack.append(self) while len(stack) > 0 and while len(visited) >= 0: current = stack.pop() array.append(current) visited.add(current) return array
def dft(self, array):
stack = Stack()
visited = set()
stack.append(self)
while len(stack) > 0 and while len(visited) >= 0:
current = stack.pop()
array.append(current)
visited.add(current)
return array
Example 4: python stack data structure
>>> from collections import deque
>>> myStack = deque()
>>> myStack.append('a')
>>> myStack.append('b')
>>> myStack.append('c')
>>> myStack
deque(['a', 'b', 'c'])
>>> myStack.pop()
'c'
>>> myStack
deque(['a', 'b'])