Showing posts with label codeinpython. Show all posts
Showing posts with label codeinpython. Show all posts

Friday, October 30, 2020

CREATING STACK IN PYTHON

CREATING STACK USING PYTHON



OPERATIONS:

1- PUSH

2- POP

OTHER OPERATIONS:

1- IS EMPTY

2- SIZE

3- TOP



CODE : 

We can implement stack using :

1- list

2- collections.deque

3- queue.LifoQueue


1 - IMPLEMENTING STACK USING LIST

CODE:

stack = []  // list is created to be used as stack
stack.append('a') // append() push the element in stack which is actually a list
stack.append('b')
stack.append('c')
print(stack.pop()) // pop() is used to pop / delete element on top of list
print(stack.pop())
print(stack.pop())

print(stack)


2- IMPLEMENTING STACK USING collections.deque


from collections import deque  // importing the library
stack = deque() // initializing a variable

stack.append('a') // append function to insert element
stack.append('b')
stack.append('c')

print(stack.pop())  // pop() function to remove the top element
print(stack.pop())
print(stack.pop())

print(stack)

3- IMPLEMENTING STACK USING queue module

Functions available in this module are :

1- get() - remove and return the element from queue
2- put(element) - put element in the queue
3- maxsize() - maximum elements allowed
4- empty() - check whether stack is empty or not
5- full() - check whether stack is full or not if maxsize is declared
6- qsize() - get number of items in queue

CODE:

from queue import LifoQueue
stack = LifoQueue(maxsize = 5)
// initializing stack with maxsize = 5
print(stack.qsize()) // show the number of elements in the stack
stack.put('a')  // put() is used to push elements in the stack
stack.put('b')
stack.put('c')
print("Full: ", stack.full())  // is the stack full or does stack contain maxsize elements
print(stack.get()) // return and remove the top element of the stack
print(stack.get())
print(stack.get())
print("Is Empty : ", stack.empty()) // test is the stack empty or not