how to create a stack in python code example
Example 1: how to create a list in java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
class scratch{
public static void main(String[] args) {
List<Integer> aList = new ArrayList<>();
List<Integer> lList = new LinkedList<>();
}
}
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: 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 5: stack in python
# Stack
class My_stack():
def __init__(self):
self.data = []
def my_push(self, x):
return (self.data.append(x))
def my_pop(self):
return (self.data.pop())
def my_peak(self):
return (self.data[-1])
def my_contains(self, x):
return (self.data.count(x))
def my_show_all(self):
return (self.data)
arrStack = My_stack()
arrStack.my_push(1)
arrStack.my_push(2)
arrStack.my_push(1)
arrStack.my_push(3)
print(arrStack.my_show_all())
arrStack.my_pop()
print(arrStack.my_show_all())
print(arrStack.my_contains(1))
Example 6: stack example in python
>>> 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