Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

CHAPTER : DATA STRUCURES IN PYTHON

STACK AND QUEUE (LIST IMPLEMENTATION)

Introduction

An essential part of programming is how the data is organized in order to


manipulate it effectively. Organization of data in an efficient way to support the
algorithm to manipulate the data is known as data structures. Basic functions
defined on the data structure are used to manipulate the data. Following is the
classification of data structures. Secondary data structures like stacks, queues,
trees and graphs are built from the primary data structures which were explained
in the earlier modules. In this module, the secondary data structures are
explained.

Figure 1: Classification of Data Structures


Stack

A stack is a linear data structure, which follows the principle of Last In First Out
(LIFO). Consider a pile (stack) of books on a table. One book may be added to the
pile or taken away from the pile at a time. The book which was placed last on the
pile (Last In) is the one which can be taken out (First Out) from the pile. An index
(called TOP) tracks the elements in the stack. TOP is initialized as -1 and
incremented as and when an element is added (known as PUSH operation) or
decremented when an element is deleted (known as POP operation) from the
stack. At any given point of time, only the top element of the stack can be seen.
There is a capacity defined for a stack in terms of the maximum elements it can
hold. When the maximum capacity is reached, one more PUSH operation gives an
error known as OVERFLOW. Similarly removing an element from an empty stack is
results in UNDERFLOW error.
STACK OPERATIONS:
A stack is described with the following operations. Each of these operations are
defined by the programmer.

push(item) : Inserts an 'item' at the top of the stack


pop() : Takes an element out of the stack
top() : Returns the element at the top
isfull() : Returns true if the stack is full
isempty() : Returns true if the stack is empty
overflow() : Returns true if an overflow exception is raised
underflow() : Returns true if an underflow exception is raised

NOTE:

1. If TOP==size and we want to push an element


into stack then OVERFLOW occurs
otherwise TOP=TOP+1
2. If TOP== -1 and we want to delete an element
from stack then UNDERFLOW occurs
otherwise TOP=TOP-1

Using List as Stack:

The list methods make it very easy to use a list as a stack, where the last element
added is the first element retrieved (“last-in, first-out”). To add an item to the
top of the stack, use append(). To retrieve an item from the top of the stack,
use pop() without an explicit index.

Example:
>>> stack = [3, 4, 5]
>>>stack.append(6)
>>>stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>>stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>>stack.pop()
6
>>>stack.pop()
5
>>> stack
[3, 4]
Program to implement a stack using list :
def push(mystack, item):
mystack.append(item)

def pop(mystack):
if len(mystack) == 0:
print ("Underflow")
else:
item = mystack.pop()
print(" Element popped is " ,item)

mystack = []

push(mystack ,5)
push(mystack ,15)
push(mystack ,25)
push(mystack ,35)
print(mystack)
pop(mystack)35
pop(mystack)25
pop(mystack)15
print(mystack)
push(mystack ,100)
print(mystack)
pop(mystack)100
pop(mystack)5
print(mystack)
pop(mystack)

'''
Output :
[5, 15, 25, 35]
Element popped is 35
Element popped is 25
Element popped is 15
[5]
[5, 100]
Element popped is 100
Element popped is 5
[]
Underflow
'''

s = Stack() # stack object


s.push(5)
s.push(10)
print(s.top()) # returns 10
s.push('CBSE')
print(s.size()) # returns 3
print(s.isEmpty()) # returns False
s.push(8.5)
print(s.pop()) # returns 8.5
print(s.pop()) # returns CBSE
print(s.size()) # returns 2

Solved example:-

P.1.#Program to implement a stack using a list


num=[]
sure='y'
while(sure=='y'):
print("1.Push")
print("2.Pop")
print("3.DISPLAY")
choice = int(input("Enter your choice: "))
if(choice==1):
item=int(input("Enter the item: "))
num.append(item)
elif (choice==2):
if(num==[]):
print("stack empty")
else:
print("Deleted element is", num.pop())
elif(choice==3):
if(num==[]):
print("Stack empty")
else:
l=len(num)
for i in range(l-1,-1,-1):
print(num[i])
else:
print("Invalid Choice")
sure=input("Do you want to continue(y/n)")
"""
OUTPUT

1.Push
2.Pop
3.DISPLAY
Enter your choice: 1
Enter the item: 10
Do you want to continue(y/n)
1.Push
2.Pop
3.DISPLAY
Enter your choice: 1
Enter the item: 20
Do you want to continue(y/n)
1.Push
2.Pop
3.DISPLAY
Enter your choice: 3
20
10
Do you want to continue(y/n)
1.Push
2.Pop
3.DISPLAY
Enter your choice: 2
Deleted element is 20
Do you want to continue(y/n)
1.Push
2.Pop
3.DISPLAY
Enter your choice: 2
Deleted element is 10
Do you want to continue(y/n)
1.Push
2.Pop
3.DISPLAY
Enter your choice: 3
Stack empty
"""
OR (MENU DRIVEN PROGRAM FOR STACK AS A LIST)

s=[]
def stkpush(s):
if len(s)==100:
print("not willing to accept more than 100 values")
else:
v=int(input("enter a value:"))
s.append(v)
print("value pushed into stack")

def stkpop(s):
if len(s)!=0:
v=s.pop()
print("value popped=",v)
else:
print("cannot pop from an empty stack")

def stkdisplay(s):
for i in range(len(s)-1,-1,-1):
print(s[i])

while True:
print("""stack operations
1.Push values
2.Pop values
3.Display
4.Exit
""")
ch=int(input("enter a choice(1-4):"))
if ch==1:
stkpush(s)
elif ch==2:
stkpop(s)
elif ch==3:
stkdisplay(s)
elif ch==4:
print("Thanks for running the program")
break
else:
print("invalid choice")
P:2 Program to reverse a string using a stack

def push(mystack, item):

mystack.append(item)

def pop(mystack,item):

if len(mystack)==0:

print("underflow")

else:

item=mystack.pop()

return (item)

def reverse(string, mystack):

n=len(string)

#Push all characters of string to stack

for i in range(0,n,1):

push(mystack,string[i])

string=" "

item=' '

#Pop all characters of string and put them back to string

for i in range(0,n,1):

string+=pop(mystack,item)

return string

mystack=[]

string="MALAYALAM"
string=reverse(string, mystack)

print("Reversed string is" +string)

P:3 Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this
list push all numbers divisible by 5 into a stack implemented by using a list. Display
the stack if it has at least one element, otherwise display appropriate error
message.
OR
Write a function in Python POP(Arr), where Arr is a stack implemented by a list of
numbers. The function returns the value deleted from the stack.

def PUSH(Arr):
Stack=[ ]
if len(Arr)!=0:
for i in Arr:
if i%5==0:
Stack.append(i)
if len(Stack)!=0:
for i in range(len(Stack)-1,-1,-1):
print(Stack[i])
else:
print("Empty Stack")
else:
print("Source List is empty")
return(Stack)

def POP(Arr):
x=-1
if len(Arr)==0:
print("Empty Stack")
else:
x=Arr.pop( )
return(x)

b=[10,7,5,18,21,25]
a=PUSH(b)
c=POP(a)
if c==-1:
print("Empty stack")
else:
print("Popped value : ",c)
Queue
A queue is a pile in which items are added on one end and removed from the
other. In this respect, a queue is like the line of customers waiting to get a ticket
in a movie counter. As customers arrive, they join the end of the queue while the
ticket issuer serves the customer at the head of the queue. As a result, a queue is
used when a sequence of activities must be done on a first-come, first-served
basis. Queue is a First-In-First-Out (FIFO) structure. When we add an element into
Queue is known as REAR and when we delete an element from queue is known as
FRONT.The queue operations are given below.

● enqueue - adds an element to the end of the queue:

● dequeue - removes the element at the beginning of the queue:


● Queue() creates a new queue that is empty. It needs no parameters and
returns an empty queue.
● enqueue(item) adds a new item to the rear of the queue. It needs the item
and returns nothing.
● dequeue() removes the front item from the queue. It needs no parameters
and returns the item. The queue is modified.
● isEmpty() tests to see whether the queue is empty. It needs no parameters
and returns a boolean value.
● size() returns the number of items in the queue. It needs no parameters and
returns an integer.

QUEUE OPERATIONS:

R=0,F=0

R=1, F=1, A

R=2, F=1 A B

R=3 ,F=1 A B C

R=4 ,F=1 A B C D
R= 5, F=1 A B C D E

R=5, F=2 B C D E

R=5 ,F= 3 C D E

R=5,F=4 D E

R=5 ,F=5 E

R= 0, F=0

NOTE: 1. if Q has no element then R=0,F=0


2. When we add an element into Q then R=1,F=1
3. if we add further element into Q then R=R+1
4. If we delete an element from Q then F=F+1
5. If R==F then Q has 1 element and
if we want to delete the element
then Q becomes R=0,F=0
6. If R==size and we want to add an
element into Q then R=0
7. If F==size and we want to delete an
element from Q then F=0

Program to simulate the core operations of a queue using append and pop
operations of the list .

fruits = []

# enqueue some fruits into the list


fruits.append('banana')
fruits.append('grapes')
fruits.append('mango')
fruits.append('orange')

# Now let's dequeue our fruits, we should get 'banana'


first_item = fruits.pop(0)
print(first_item)
# If we dequeue again we'll get 'grapes'
first_item = fruits.pop(0)
print(first_item)

# 'mango' and 'orange' remain


print(fruits)

However, lists are not efficient for this purpose. While appends and pops from the
end of list are fast, doing inserts or pops from the beginning of a list is slow
(because all of the other elements have to be shifted by one).

Program to implement a queue using list

def insert(myQ, item):


myQ.append(item)

def Delete(myQ):
if len(myQ) == 0:
print ("Underflow")
else:
item = myQ.pop(0)
print(" Element deleted is " ,item)

myQ = []

insert(myQ ,5)
insert(myQ ,15)
insert(myQ ,25)
insert(myQ ,35)
print(myQ)
Delete(myQ)
Delete(myQ)
print(myQ)
insert(myQ ,100)
print(myQ)
Delete(myQ)
Delete(myQ)
print(myQ) 100
Delete(myQ)
print(myQ)
Delete(myQ)
'''
Output :
[5, 15, 25, 35]
Element deleted is 5
Element deleted is 15
[25, 35]
[25, 35, 100]
Element deleted is 25
Element deleted is 35
[100]
Element deleted is 100
[]
Underflow
'''

Solved example:-

P.1. #Program to implement a queue using a list


num=[]
sure='y'
while(sure=='y'):
print("1.Add")
print("2.Delete")
print("3.DISPLAY")
choice = int(input("Enter your choice: "))
if(choice==1):
item=int(input("Enter the item: "))
num.append(item)
elif (choice==2):
if(num==[]):
print("queue empty")
else:
print("Deleted element is", num.pop(0))
elif(choice==3):
if(num==[]):
print("Queue empty")
else:
l=len(num)
for i in range(0,l,1):
print(num[i])
else:
print("Invalid Choice")
sure=input("Do you want to continue(y/n)")
"""
OUTPUT
1.Add
2.Delete
3.DISPLAY
Enter your choice: 1
Enter the item: 10
Do you want to continue(y/n)
1.Add
2.Delete
3.DISPLAY
Enter your choice: 1
Enter the item: 20
Do you want to continue(y/n)
1.Add
2.Delete
3.DISPLAY
Enter your choice: 3
10
20
Do you want to continue(y/n)
1.Add
2.Delete
3.DISPLAY
Enter your choice: 2
Deleted element is 10
Do you want to continue(y/n)
1.Add
2.Delete
3.DISPLAY
Enter your choice: 3
20
Do you want to continue(y/n)
1.Add
2.Delete
3.DISPLAY
Enter your choice: 2
Deleted element is 20
Do you want to continue(y/n)
1.Add
2.Delete
3.DISPLAY
Enter your choice: 3
Queue empty

"""

*******
Example :1

Conversion of a decimal number to binary. The idea is to define a function which


uses a stack internally to get the job done.

def push(mystack, item):

mystack.append(item)

def pop(mystack,item):

if len(mystack)==0:

print("underflow")

else:

item=mystack.pop()

return item

def dec2bin(decnumber, mystack):

while decnumber>0:

rem=decnumber%2 #get the remainder and push

push(mystack,rem)

decnumber=decnumber//2 #repeatedly divide

item=0

while mystack: #get the remainders from the stack

print(pop(mystack,item), end=" ")


mystack=[]

num=int(input("Enter the number"))

dec2bin(num,mystack)

OUTPUT

Enter the number354

1 0 1 1 0 0 0 1 0

The function dec2bin can be modified to convert numbers with any base.

You might also like