stack in 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
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
# 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))
# Python Script to Implement two stacks in a list
class twoStacks:
def __init__(self, n): # constructor
self.size = n
self.arr = [None] * n
self.top1 = -1
self.top2 = self.size
# Method to push an element x to stack1
def push1(self, x):
# There is at least one empty space for new element
if self.top1 < self.top2 - 1 :
self.top1 = self.top1 + 1
self.arr[self.top1] = x
else:
print("Stack Overflow ")
exit(1)
# Method to push an element x to stack2
def push2(self, x):
# There is at least one empty space for new element
if self.top1 < self.top2 - 1:
self.top2 = self.top2 - 1
self.arr[self.top2] = x
else :
print("Stack Overflow ")
exit(1)
# Method to pop an element from first stack
def pop1(self):
if self.top1 >= 0:
x = self.arr[self.top1]
self.top1 = self.top1 -1
return x
else:
print("Stack Underflow ")
exit(1)
# Method to pop an element from second stack
def pop2(self):
if self.top2 < self.size:
x = self.arr[self.top2]
self.top2 = self.top2 + 1
return x
else:
print("Stack Underflow ")
exit()
# Driver program to test twoStacks class
ts = twoStacks(5)
ts.push1(5)
ts.push2(10)
ts.push2(15)
ts.push1(11)
ts.push2(7)
print("Popped element from stack1 is " + str(ts.pop1()))
ts.push2(40)
print("Popped element from stack2 is " + str(ts.pop2()))
# This code is contributed by Sunny Karira
>>> 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