0 ratings 0% found this document useful (0 votes) 7 views 20 pages Data Structures
The document provides an overview of data structures in Python, focusing on lists and stacks. It explains the characteristics and operations of stacks, including push and pop operations, and their dynamic nature. Additionally, it discusses practical implementations and applications of stacks, such as reversing words and evaluating arithmetic expressions.
AI-enhanced title and description
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save data structures For Later
~ Data Structures
in Python
A
5.1 INTRODUCTION
Every programming language provides salient features of data structures. A data structure is more
precisely defined as a way of storing, organizing, accessing, and retrieving data in a computer
so that it can be used most efficiently to give optimal performance. For example, string is a data
sructure containing a sequence of elements where each element is a character. On the other hand,
fist is a sequence data structure in which each element may be of different type. We can apply
different operations like traversal, reversal, slicing, counting of elements, etc., on strings and lists.
Hence, a data structure organizes multiple elements in such a way that certain operations on each
dement as well as the collective data unit could be performed easily. There are several types of
data structures which are designed and used for different kinds of applications.
‘CIM: A Data Structure is a named group of data of different data types which is stored in a specific way and
‘an be processed as a single unit. A data structure has well-defined operations, behaviour and properties.
In Class XI, we have studied about an important sequential linear data structure, list, which is an
ordered sequence of items. When we intend to refer to or access a specific value in the sequence/
list, it is done using index value or subscript and is accessed from the 0* position till last index - 1.
jie, they can grow /increase and shrink/decrease in size/number
terogeneous, which means we can store elements
nsiderable differences between data type
Python lists are dynamic in nature,
of items as and when required. They are also het
of multiple data types in a single list. But there are co
and data structures in Python which are as follows:
+ Data Type defines the type of values we can store and operations we can perform on those
values. For example, in int data type we cannot store decimal values and we cannot multiply
two string type values. It also specifies the amount of memory it will take.
On the contrary, Data Structure is the physical implementation that clearly defines a way of
storing, accessing and manipulation of data stored in data structure, Every data structure
has a specific way of insertion and deletion, like Stack works on LIFO (Last In First Out), fe,
all operations will take from one end, e., TOP, whereas QUE 0
Out), ie., item inserted first will be removed first al v
end of Queue.
In this chapter, we shall further discuss two data s
implementation in Python using lists.St 2
5.2 STACK
ich insertion a
AStackisalinear/sequence srucureoralistafeenetsinv LIFO (lastin, fre
‘only at One end, Le, Stack's top. Because of this, Stack is ee betas oe ut) dary
LIFO means the element Inserted last would be the firs the coin placed at thes a)
For example, a stack of coins, where we can remove only the coin p| St ig 54)
of the applications of Stack in real life are: .
* Can of Tennis balls
Pile of clothes in an almirah
Bangles worn on wrist
+ Stack of Plates
* Multiple chairs in a vertical pile
*+ Pile of boxes of eatables in a pant
°Y or ong it
oe 2 “Ss Top—> | |
Stack of Coins
Stack of Plates Can of Tennis Balls
Stack of Books
Fig. 5.1: Everyday Analogy of a Stack
Features of stack:
A stack has the following features;
1. Stack is a simple linear data structure that provides only one end for entry and exit Of
2. No element can be accessed from the middle.
3. Itworks on Liro Cast In, First Our
retrieved first from it.
Stat performs two major operations,
(@_ When an element is inserted/ada.
(i) When an element is deleted/rem
To perform the ab
Of the Stack, ie, 7
) principle. The element entering last into the Stackway
viz. PUSH and POP.
led on top of the Stack, it is
loved from the top of the Stack, it is called POP ‘Operation
rations, we need to declare a
torage location or a container
called PUSH Operation,
ove two major ope
OP, and acts as a sl
variable that points to te
to store elements of thetexadent from Fig. 5.2. the two Stack operations are performed through th: *top'—ek ts
S pserced as well as deleted from the top only en
wr Smack isa dynamic data structure 2s it grows (with an increase in the number of elements) or
acs (wth 2 decrease in the number of elements) A static data structure, on the other hand, is
Se Sat bas a fixed size.
_qu3s are fendamentully important as they can be used to reverse the order of items or elements.
ae ecder of insertion is reverse of the order of removal Fig. 53 shows the Python data object
qgck created in the original order and traversed/deleted in the reverse order.
Fig. 5.3: Reversal Property of Stack
(ue of the most frequently used applications of Stack that we encounter in our day-to-day life is
wien a user browses the internet for information retrieval. While navigating a website, web page
‘» web page, these pages are placed on a Stack or, in other words, the URLs are placed on the
Sac The current page that you are viewing is on the top and the first page you looked at is at
Se bottom. Now, when we click on the ‘Back’ button, we begin to move in reverse order through
Se pages. Thus, this browsing process is implemented through Stack.
Een the compilers that are conferred with the job of debugging and translation also use Stack for
evaluating expressions, generating machine code and during function calls.
x3 IMPLEMENTATION OF STACK USING LIST
Tie implementation of Stack using list in Python i is the easiest of all programming languages. It
sGers a convenient set of methods to e a The basic operations performed on
the Stack are: ,
1 Creating a Stack
2 PUSH Operation/Adding Ele
3. Checking the Status of Stacl5.3.1 Creating a Stack
The built-in data structure list available in Python makes it flexible and easy to implem,
Python, when we declare/create a list, it creates an address in memory and can hig «"S&
of heterogeneous elements. Thus, in order to create an empty Stack, we just neeq es Tang
function list() or {] as per the syntax given below. se
The syntax is:
Stack =list() #an empty stack/list
OR
Stack = [] fan empty stack/list
Here, in the first line of code, Stack is a variable of list type and is created using list) funcg,
in the second line of code, Stack variable is created by assigning an empty pair of square by
Like lists, in order to access the elements ina Stack, index values are used. Thus, the fis
in the Stack will be Stack{0], the second will be at Stack{1] and so on. Unlike lists, Tandon
is not allowed for the objects contained in the Stack. sy
5.3.2 PUSH Operation/Adding Elements into a Stack
Adding/Inserting a new element to the Stack list is called PUSH operation. In Python, the
function append() is used to add elements into the Stack. The syntax is: &
Syntax: Stack. append (x)
Here, x is the element to be inserted into the Stack and is inserted at the end of the list ‘implemen
as a Stack. If Stack is an empty list, it simply appends this first element to the Stack.
Note: Attempts to insert an element into a full Stack, ie,, (Top=n-1), where nis the size oft
Stack, is called Stack Overflow.
Algorithm for PUSH Operation
The steps to be performed for carrying out the PUSH operation on the Stack are as follows:
1. START
2. Stack-list() or Stack=[] # Initialize a Stack using list
3, element = input(“Enter the value to be added in the stack :”)
4, Stackappend(element) #Adding element into list
5. END
While we perform PUSH operation into the Stack, we push the ‘element’ onto the Stack 68
append() function, ,
5.3.3 Checking the Status of Stack
To use Stack efficiently, we need to check the status of Stack as well. For the same P
following functionality is added to Stack:
() peek()—peek() is a user-defined function used to get the most recent vallle
ie, top element of the Stack without removing it or value at the top. It will throw
if the Stack is empty or null.
(i) Overflow—To check if Stack is full which leads to overflow while trying to insert
in the Stack. In Python (for stack and queue implemented as list), since.
overflow condition will arise until all memory is exhausted.
(ii) Underflow—To check if Stack is empty which leads to underflow
element from the empty Stack.Algorithm to display top element without deleting it, Le., peek()
1, START
2, iflen(Stack) == 0:
print("Underflow”)
3. print(Stack[len(Stack)-1])
4, END
Algorithm to check if Stack is empty
1, START
2, Stlen = len(Stack)
3, if Sten == []:
print(“Underflow")
4, END
5.3.4 Pop Operation/Deleting an Element from a Stack
ap Python, the list function pop() is used to pop/remove/delete elements from a Stack. The syntax
st
[Link]()
Here,
« The function pop() removes the last element which is on the top of the Stack.
« Italso returns the popped/deleted elements from the list.
Therefore, in order to delete an element from the Stack, no subscript/index value is required to be
passed to the function pop(). If a user tries to delete an element from the empty Stack, it is called
underflow of Stack.
Algorithm to delete an element from a Stack
Steps to be followed are: or
1. START ‘
2. Stlen =len(Stack) #Count the total number of elements in the Stack
#Checks whether the Stack is empty or not t
3. ifStlen==[]: or ifnotStack: or ifnotlen(Stack):
print(“Stack is empty”)
go to step 6
4. element = [Link]() #Removing last element from top of the Stack
5. print(element)
6. END
In case of non-empty Stack only, the element shall be rem
built-in function pop() that removes last element.
> Once an element is popped, the Stack automatically red Ic
~98GGH— data Structures in Pythones as a collection of eleme
:
serv a |
5.3.5 traversing/D that a Sta yrement to the collection, and pop(), wh
: re have understood 0 which adds an moved. In order to check the a
wo pric eran 4 t was not yet re! sa eee :
ith two principal oP d element tha’ i are performed, versal of g,
aoe the most recent ce er PUSH and POP ont Rae ts from the top position, ie 5
stack whene ess, the elemen 1 18
clean eae tory. In traversal process
é i der.
aa y cas ayed and processed in the reverse ©
serted element,
gorithm for traversing Stack Elements: .
_ START
[= Ien(Stack)
for iin range(I-1,-1,-1):
print(Stack[i])
End
ctical Implementation-1
e a Python program to implement all basic operations of a Stack,
5 - , , such as addii
H operation), removing element (POP operati ger ing element
ed sie ( eration) and displaying the Stack elements (Traversa
lementation of List as stack
2 (omy):
print("1. PUSH")
print ("2. POP ny :
cewint (input ("
£ (choice == a ‘Enter your choice: 1)
nput ("Ente:
rie {append (a) x an element
£ (choice==2) ;
42 (omer):
Print(*
alee int ("Stack as
_(ctian (Beteted element
i su
"len (s) a
>
se:
PFint ("te9,
input ("Do oe yeiapueyja. PusH
2. POP
3. Display
Enter your choice: 1
Enter an element :66
Do you want to continue or not? y
1. PUSH
2. POP
3. Display
Enter your choi
Eater an element
Do you want to continue or not? y
a. PUSH
2. POP
3. Display
Enter your choice: 3
6 -
id
5
Do you want to continue or not? y
i. PUsH
2. POP
3. Display
znter your choice: 2
Deleted element is 88
De you want to continue or not? y :
| a. PusH
2. POP
| 3. Dispray 6
| gnter your choice: 3 3
6s
i anys
's
|p you want to continue or not?
>»
Practical Implementation-2
Write a program to display unique vowels present in the given word using Stack.
Farite a program to display unique vowels present in the given word
(fusing Stack
Iewes = 'n1, tate tg tote 121
lvord = input ("Enter the word to search for vowels :") 8
stack = []
for letter in word:
ig letter in vowels:
if letter not in Stack: e
stack. append (letter)
eesne(Bkaek), 4,
print("The number of different vowels present in’ word, "is", len (stack))
Output:
Enter the word to search for vowels :Hello
eae
‘The number of different vowels present
>>>|
Explanation:
In the above program, we have to find the
word. This is done by comparing each lett
Vowels are added to the Stack (only uniqi
container to hold all the vowels wl
len(Stack) function with print()
~90BGG— osta structures in Python:Practical Implementation-3
Write a program to create a Stack called Employee, to perform the basic operatio,
list. The list contains the two values—employee number and employee name,
include the options for addition, deletion and display of employee details.
NS on, Stagy
tiie Programs hy
muy
Program to add, delete and display the records of an Employee using 1gq¢
#iimplementation through stack
Employee=[]
ory"
while (c == "y"):
print("1. PUSH")
print("2. PoP")
print("3. Display")
choicesint (input("Enter your choice: "))
© _d@=input ("Enter Employee no :")
ename=input("Enter the employee name
if (Employee == []):
Print("stack Empty")
else:
eid, ename = [Link]()
print("Deleted clement is: ",e id,ename)
elif (choice = 3): a
imlen (Employee) z
while 4> 0: #T0 display elements from last element to first
print (Employee[i-1])
iea-a
else:
Print("Wrong Input")
eminput("Do you want to continue or not? ")
Enter Employee no :2
[Enter the employee name :Shaurya
|Do you want to continue er not? y
1. PUSH
2. POP ’
|3. Display é
(Eater your choice: 1 “ a
|gnter Employee no :4 990i) taeyased on the above concept learnt on push, pop, and traversal of a stack, trace the output based
wn the given code:
(a) result=0
numberList=[10, 20, 30]
numberList .append (40)
result=result+numberList .pop()
result=result+numberList .pop()
print ("Result=", result)
Ans: Result = 70
(b) answer=[]; output=' '
answer .append('T')
[Link]('A')
[Link]('M')
ch=answer .pop ()
output=output+ch
ch=[Link] ()
output=output+ch
ch=answer .pop ()
output=output+ch
print ("Result=", output)
Ans: Result = MAT
Applications of Stacks
some of the important applications of Stacks include:
1, Reversing a Word/Line: A simple example of Stack application is reversal of a given line. This
can be accomplished by pushing each character on to a Stack as it is read. When the line is
finished, characters are popped off the Stack and they will come off in the reverse order.
Conversion of decimal number to binary is also done using Stack.
2. Evaluation of Arithmetic Expressions: A Stack is a very effective data structure for evaluating
arithmetic expressions in programming languages. An arithmetic expression consists of
operands and operators. It may also include parentheses like “left parenthesis” and “right
parenthesis”, Stack is used to evaluate these arithmetic expressions on the basis of operator
precedence (BEDMAS - Brackets off; Exponentiation; Division/Multiplication; Addition/
Subtraction). mer
3. Processing Function Calls: The com
when a function is called or during
4. Backtracking: Backtracking is a
out of the possibilities. Backtr
optimization problems such
. Undo Mechanism in Te6 rcrnaernan mma DS '
the navigation history that enables users to move back and forth between the recently
pages. The pages visited by the user are added to the Stack on the top of one ancther et
allowing a user to go to the previous page by clicking the BACK button in the browser whice
retrieves the previous page stored at the top of the Stack.
5.4 QUEUE*
In the previous topics, we have discussed implementation ° °
of Stack. Now, we will learn implementation of Queue with 17 5
Python list. Le
Queues are similar to Stacks in that a Queue also consists of
a sequence of items (a linear list), but there are restrictions 1
on how items can be added to and removed from the list. i
Queue permits deletion to be performed at one end of the
list and insertion at the other. Fig. 54: A Queue
a,
We see queues in our day-to-day life at various places such as:
+ Bank ATM
« Fee counter
* Shopping centre
‘+ Students standing inside school premises during morning assembly
+ Customers forming queue at the cash counter in a bank
+ Vehicles queued up at fuel pumps
In all of the above cases, the person who has waited the most shall withdraw the money first or
pay the fee first. As shown in Fig. 5.4, the first person in the queue is served first and others can
enter the queue only at the end. Thus, a Queue is called FIFO (First In, First Out) data structure,
where the item first inserted is the first to get removed (Fig. 5.5).
2 a 4 5 6
= [+]: is
index—> 0 1
= no
—— as
—
a Deletion from Queue
First in, frst TA
Fig. 5.5: A Queue in Python
Thus, Queue is also known as a First Come First Served (FCFS) appr
A Queue consists of two open ends—Front and Rear (Fig. 5.5). _
1, Data can only be removed from the front end, ie, the
2. Anew data element can only be added to the rear end 0
‘atin yiahas at Wainer ea Ta- "sf
—_ = a i.
yet In Python, an empty tis a one ih fz
ws a Queue, 1S create :
When we implement default ist as
asshown in Fig.5.6(@).Itshows gs See te
Ian elements to be insert,
element is carried out fro
an
nea sth ont are placed at 0% Position of the Queue
ed in this Gee - index Value. ti m 0 with no elements,
= »Ithas tobe done fro
t ci mth
daa obect of eterogeneus un pew Fie, 5.605). Lie a
.
“Pieerers
end and deletion of an
tack, Queue also holds
0 insertion
Deletion from front end amiss 0 sg
Fig. 5.6(b):
56(B): A Queue Holding Heterogeneous Data in Python
TM: Queue isa linear data structure that follows FIFO policy
5.5 IMPLEMENTATION OF QUEUE AS LisT*
(@) Creating a Queue using List
(0) Inserting an element in a Queue (Enqueue) |
(6) Checking the status of Queue
(4) Deleting elements from a Queue (Dequeue)
(€) Traversal/Displaying Queue items
aes)
Whenever we create a list in Pe i
of heterogeneous elements. Like @
‘same manner Queue is created.
=
Nota syllabus bur retained for extra eatinae ee nk ae al ak
be implemente,
‘The Queue created using lis() method is shown below and can be imp| 485 nea
of a Queue,
s
oes
Giese = ist)
OR
Queue = [.
Herein the first line of code an empty Queue is created asa varlable of ist type an
id Inthe
Hine of code, Queue variable is an empty Queue as it does not contain any element Seay
The first element added tothe Queue will be at Quewe[0},
0, followed bby the second element at Queue}, where front
by and shall point to inde 1 and so on.
here both front and reap
Ibe at 0 and rear shat},
fo
5.5.2 Inserting an Element into a Queue (ENQUEUE)
Enqueve operation is
elements inthe queue:
beyond capacity will
used to insert a new element to the queue at the rear end, We 2g
till there is space in the queue for adding more elements. isertng denne
esult in an exception known as OVERFLOW.
‘Inserting an element into a Queue takes place using REAR; REAR will be incremented iggy
fe new value in Queue. in Python, thelist function append) le used tr, ad elements ogi
‘Suppose we want to insert 5 elements, 3¢ ‘ina Queue. Then the followir
the insertion of elements i
Eps
ina Queue using a list. Also, the position of rear gets char
step of insertion
ed ate,
Step 2: To begin with an empty Queue, with both front and rear at the same position,
‘An empty Queue
OSAP Raat baie,
oer
Step 2: Insert the fist element 25 38 nto the Queue with front = 0 and rear = 9,
from =0
UA UE aie tgoeae
‘he Queue with front= 0 and rear =
x
Digaat
ae ets BTA
Step 4:1
PA: Insert another element 45 nto the Queue with front =ss
gg nave reroll te
M6 Si Sigs A em mimmneces en Apso we
98 OE eT BOE CE rae) cet : :
es ce fens Dooce Smesand am the ween ae Si mse ae re aT
Oo oe ce ast CORTE. CONE emesis line SP Scone semaine ‘tae sere a 0 Soe, wets
So ee ue fneerting au clot peice dc Quen nat ee att Re
‘Quemeis ed
Zz ig used 10 20d Hlemems 39 tie alee Eanqueue in Petton. 1
gts =
© pent - 222
ne cement to be inserted at che
a ‘i : Beas ct poste wo tee ecu E Space Sao EE
ea POPS CRIES 8 Oi nel a ae
prov co insert. am cet Sate aie tone
pir im i PARI GPCI) Me ee te ae ea
pyaar 00 append Paes ie aee aes sent en
5 SORT
b gerne tis or Quene=() Finttalce 2 Queue mig se
| ement = input] Eater the clement to te atiiet a0 tie Queue)
453 Caecking the Quese States
He ldewg, cometcocts 5 SO as
fm.
fas any Semmes or mar so 25 In aEfrom the queue. My,
Algorithm to display first element without deleting it, Le, peek(}:
1. Start
2 if Queue ==[}
rint("Queue is Empty")
Goto steps
3. print(Queuefo})
4 End
(ill) Overflow: It is used to check whether any more element can be adde
tthe ay,
ot to avoid overflow exceptions while performing enqueue operatio a
5.5.4 Deleting Elements from a Queue (DEQUEUE)
Before deleting an element from a Queue, it becomes mandatory to check
empty oF not as it becomes insignificant if the Queue is empty. If the Quet
Temove element{s) from the front end of the Queue.
k whether the
ue is non-em
ee
my
‘The deletion/removal ofan elementin a Queue is done from the front end. Delet
ng an element ng
the Queue is called Dequeue. used 0 remove one elementatatime om the FRONT fees
We can delete elements from a queue unt it is empty. Trying to delete an element fom ane
eg wil esultinan exception known as UNDERFLOW. hiss performed using the rte
function del/popQ, which is used to remove elements from a Queue, The s
‘Queue. pop (0)
syntax is
del Queue[0] #as deletion will alvays take place from 0 index positian
+ Inthe first statement, we have deleted an element
of the list is 0 which deletes the element from tl
deleted element from the Queue,
‘+ Inthe second statement, we have deleted an element using del keyword where the positing!
the lst is 0 but del keyword does not return the deleted element.
‘To begin with deletion operation using front end ofthe Queue,
‘The O* position is the first position in the Queue. When we
function, it will remove that element and shift al the elements
the removal ofthe element from the Queue and shall return
using the pop(0), the position or index
the front end. It also allows us to rete
we should use the pop (0
delete an element using th
after it to ‘fill the gaps’ et
the value which was
Algorithm to delete an element from a list Queue
1. START
2, if Queue ==} # Checks whether th
print(*Queue is Empty")
go to step 4
3. element = Queue po
OR del Queue(o}
4. print(element)
END
Queue is empty oF not
P(0)_# Deleting an elementet us understand this process using the same example of a list Queue which wi
erforming insertion of elements into the Queue, The list Queue, which we need Reet e ins
section, holds 5 elements, viz. 38, ‘A’, 4.5, 99, ’X’. To remove these elements one by one from the
queue front, the following steps are to be taken along with the value changed for front and rear
position:
step 1: A Queue consists of five elements as shown:
front =0
rear=4| 38 | ‘W | 45 | 99 | x
0 1 2 3 4 5
step 2: Execute pop(0) or pop(front) function to delete/remove front element, which is 38.
front = 0
rear=4
45 | 99 | 4
oO 1 Zz 3 4 5
rear
after deleting the front element, i.e., 38 from the Queue list, the remaining elements automatically
adjust by shifting one position to the left to fill the gap left by the deleted element 38.
front
rear=3| ‘A | 45 | 99 |
0 1 2 3 4 5
rear
step 3: Use pop(0) or pop(front) to remove front element, i.., ‘A’ from the Queue list.
45 | 99 | ’x
After deleting the front element, ie., ‘A’ from the Queue list, the remaining elements automatically
adjust by shifting one position to the left to fill the gap left by the deleted element ‘A.
x | al
2 3 4 5
rear
ep 4: For deletion of the next element, again pop(0) or pop(front) is used to remove front i
lement, i.e., 4.5 from the Queue list.
front =0
rear=2
ster deleting the front element, ie., 4.5 from the Queue list, the
adjust by shifting one position to the left to fill the gap left by
$8GO— v:ta structures in Pythonmove trom Mernuem,
Stop Bi Again, opt) or pop(tront) is used Ww Fem Ja,
"hy
(Queue Het, ERR EER ee 4
front «0 | 1 | he |
tones ot eet |
to |
the Queie Ist, the remaining emery
Alor deleting the front aloment, Le, 99 from : dae |
Aulus by shitting one position to the loft to fill the gap left by y ernens yy ?
front» 0( i a |
tanr = 0 se) |
CP ae pe gee
rear
Step 6: Now, for deleting the last element from the Queue list, use pop(y I) or Poon
front element, Le, 'X’ from the Queue Het, i,
front of
rarso| ‘®
Od at SB Iaiora Peng
rar
After deleting the front Glement, Le, x’ from the Queue list, the Queue becomes
Queue, ?
‘An empty queue |
wae 3 |
So, we have performe
d 5 deletion ope
Queue,
rations (also called DEQUEUE) which FeSUItS in a9
5.5.5 Traversal of Queue Elements
Like Stack, the elements
termed as Queue Travers
the length of th
‘length Then,
of a Queue can also be accessed and displayed and the Proce
al, For traversing each element of the Queue, we will first
@ Queue using the built-in function len() and shall
using for loop starting from
store it in the eae
O index to ‘ten, Ih, the elements
the Queue, ~ x “inde
*
Algorithm for traversing Queue Elements; 3
+ START
2
» length = len(Queue)
3, for tin Fange(0,length);
Print(Queue(i})
4 End :
We will now write a complete Python Program to Perform al} thea
practical Implementation-4*
write a program in Python to add, delete and display elements from a Queue using list.
preplementing List as @ Queue using function - pop)
Silo Comey"):
print("i. INSERT")
print("2, DELETE ")
print("3. Display")
| choice = int (input ("Enter your choice: *))
Af (choice ==1):
Deint (input ("Enter new number
| a. append (>)
elif (choices=2):
Af (amet):
‘print ("Queue Empty")
”
‘print("Deleted element is:", a[0})
[Link](0)
elif (choice —=3)?
2 = 1en(a)
for 4 in range(0,1):
print(a({i])
es
Print("wrong input")
erinput("Do you want to continue or not: ")
po you want to continue or not: y
‘Worn syllabus but retained for extra
~ 9006 — Data structures in PytZz
100k Id,
f a Queue coe
elements,
SProgram to add, remove and display the book details using lisp
fimplementation as a Queue
Librarye[]
ial
while (c == 'y'):
print("1. INszRt")
Print("2. DELETE")
Print("3. Display") ; *
choice = int (input ("Enter your choice: "))
if (choice ==1):
book_id = input("znter book_id: ")
bname = input("znter the book name :")
Lib = (book _id, bname) #tuple created for a new boox
Library append(1ib) fnew book added to the list/queue
elif (choice==2):
if (Ldbraryee(}):
print("Queue Empty")
else:
print("Deleted element is
elit (choice ==3):
1 = len (Library)
for 4 in range (0,2):
print (Library[i])
Practical Implementation-5*
Consider the details of the books where they entered in a Queue. Book details like
name are added to the Queue. Write a program to perform the basic operations o|
where the basic operations include inserting, deleting, and showing the Queue
, Library. pop(0))
else:
print ("wrong input")
© = input ("Do you want to continue or not: ")
Do you want to continue or not: y
1. INSERT
2. DELETE
3. Display
lmnter your choice: 1
Rnter book_id: 44
Enter the book name :Java
Do you want to continue or not: y
2. INSERT
2. DELETE
3. Display
Ignter your choice: 4
'Rnter book_id: 8
gntex the book name :¢++
[De you want to continue or not: y
2. INSERT
2. DELETE
3. Display
Enter your choice: 4
imnter book_id: ¢
lEnter the Book name :Wetworking
[De you want to continue or not+
‘Not in syllabus but retained for extra learning|3. Display
ater your choice: 3
j2!, ‘eython')
[e4a', saava'y
[Ust, test
|06", Networking")
pe you want to continue or not: y
4. INSERT
2. DELETE
|s. Display
gater your choice: 2
|peleted element is: ('2', ‘Python')
po you want to continue or not: y
|. INSERT
2. DELETE
3. Display
\gnter your choice: 2
|peleted element is: ('44', ‘Java')
| jpo you want to continue or not: y
(a. INSERT
2. DELETE
3. Display
gater your choice: 3
(5, 'ct")
(6', 'Networking')
ipo you want to continue or not: n
applications of Queues*
like Stacks, Queues are also an important data structure in Python. The varied applications where
queues are used are as follows:
4, Printer Queue: Queues are very useful in multi-user environment, such as in the case
of a Network Printer where there are multiple requests for print operation generated
by several users on the network, If the printer is busy, then successive requests for printing
are spooled to the hard disk where they wait in a Queue until the printer becomes available.
‘Queue ADT (FIFO)
i Yo
ee
Network Printer
2. Single-User Operations: Queues are also processor systems where only one user
can be allowed to work on the 1. F sers requesting to work on the system are
placed in a Queue. as .
Handling of Interrupts in R I-tim 2m, interrupts may occur (usually
through a mouse click or wire! immediately
before executing the current tas! ‘handle ‘as they
“Notin syllabus but retained for extral
“COG — pista structures inP=
Managing Concurrent User Requests: Suppose there is a web-seryer hostj
aces result(s). This server can handle a maximum of 50 concu;
Ba
Tent "eguesy
result(s). So, to serve thousands of user requests, a Queue would be the Most. & %
data structure to use.
5. Simulating Wait: Call centre phone systems use a Queue to hold People inline
representative gets free.
6. Playlist Ordering: Buffers on MP3 players and portable CD
players, iPod Pray
songs to the end and play from the front of the list.
eee Aas)
® Allist isa collection of elements which are stored in a sequence.
> AStackis linear structure implemented in UFO.
only at one end, ,, the Stack’s top,
> An insertion in a Stack is called
> Push operation refers to inserti
(Lastin, First Out) manner where insertions and
“elton,
Pushing and a deletion from a Stack i called popping.
ing data at the top of the stack,
> Pop operation refers to deleting/removin
> Traversal of a Stack means visitin
> ‘Stack Overflow condition means
> ‘Stack Underfiow condition means
16 data from the top of the Stack.
3 and accessing each element ofthe Stack in a specific order,
an attempt to push an element on a Stack that i already full,
* an attempt to remove/pop an element from an empty Stack,
1. Fill in the blanks,
(2) Pile of books in the library is an example of ..
(b) Ina Stack, if a user tries to
{c) Reversing the order of ite
without deletion is defined as
data type for creating and handling Stack,
5 ‘ype of data structure,
(d) Stack is implemented
{€) popt) method is
(f) Stack does not
(8) Push operat ‘
(h) Stack eaten eee ‘underflow