python has a built-in stack data structure defined under the module stack.py code example
Example 1: 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 2: stack using array python
class ArrayStack:
def __init__(self):
self._data = []
def __len(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def push(self, e):
self._data.append(e)
def pop(self):
if self.is_empty():
raise Empty('stack is empty')
else:
return self._data.pop()
def top(self):
if self.is_empty():
raise Empty('Stack is empty')
else:
return self._data[-1]
@property
def data(self):
return self._data
class Empty(Exception):
pass
Example 3: stack program in python 3
>>> myStack = []
>>> myStack.append('a')
>>> myStack.append('b')
>>> myStack.append('c')
>>> myStack
['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 empty list