Unit -4
Data Structures
[Stack]
What is Data Structure
Data Structure can be defined as the group of data elements
which provides an efficient way of storing and organizing data
in the computer so that it can be used efficiently.
A data structure is a specialized format for organizing,
processing, retrieving and storing data.
In computer programming, a data structure may be selected or
designed to store data for the purpose of working on it.
examples of Data Structures are : Stack, Queue, etc.
Data Structures are widely used in : Operating System,
Compiler Design, Artificial intelligence, Graphics and many
more.
Python Data Structure
List: Structure
It is a collections of items and each item has its own index value. Index of first
item is 0 and the last item is n-1.Here n is number of items in a list.
Creating a list
Lists are enclosed in square brackets [ ] and each item is separated by a comma.
e.g.
list1 = [‘English', ‘Hindi', 1997, 2000];
list2 = [11, 22, 33, 44, 55 ];
list3 = ["a", "b", "c", "d"];
Access Items From A List
List items can be accessed using its index position.
e.g.
list =[3,5,9]
print(list[0])
print(list[1])
print(list[2])
print('Negative indexing')
print(list[-1])
print(list[-2])
print(list[-3])
Output
3 5 9
Negative indexing
9 5 3
Important methods and functions of List
Function Description
list.append() Add an Item at end of a list
list.extend() Add multiple Items at end of a list
list.insert() insert an Item at a defined index
list.remove() remove an Item from a list
del list[index] Delete an Item from a list
list.clear() empty all the list
list.pop() Remove an Item at a defined index
list.index() Return index of first matched item
list.sort() Sort the items of a list in ascending or descending
order
list.reverse() Reverse the items of a list
len(list) Return total length of the list.
max(list) Return item with maximum value in the list.
Stack
A stack is a linear data structure in which all the insertion and deletion of data / values are
done at one end only.
➢It is type of linear data structure.
➢It follows LIFO(Last In First Out)
property.
➢Insertion / Deletion in stack
can only be done from top.
➢Insertion in stack is also known
as a PUSH operation.
➢Deletion from stack is also known
as POP operation in stack.
Applications of Stack:
• Expression Evaluation: It is used to evaluate prefix, postfix and infix
expressions.
• Expression Conversion: It can be used to convert one form of
expression(prefix, postfix or infix) to one another.
• Syntax Parsing: Many compilers use a stack for parsing the syntax of
expressions.
• Backtracking: It can be used for back traversal of steps in a problem solution.
• Parenthesis Checking: Stack is used to check the proper opening and closing
of parenthesis.
• String Reversal: It can be used to reverse a string.
• Function Call: Stack is used to keep information about the active functions or
subroutines.
Using List as Stack in Python
The concept of Stack implementation is easy in Python, because it
support inbuilt functions (append() and pop()) for stack
implementation. By Using these functions make the code short and
simple for stack implementation.
To add an item to the top of the list, i.e.,
to push an item, we use append() function and
to pop out an element we use pop() function.
These functions work quiet efficiently and fast in end operations.
Example of Stack program
stack = [5, 9, 3]
stack.append(7)
stack.append(11)
print(stack)
print(stack.pop())
print(stack)
print(stack.pop())
print(stack)
OUTPUT
[5, 9, 3, 7, 11]
11
[5, 9, 3, 7]
7
Push Operation: Stack implementation in python
# Creating a stack #Display Records of Stack
def create_stack(): def Display(stack):
stack = []
if len(stack)==0:
return stack
print("Stack is empty")
# Adding items into the stack else:
def push(stack, item): top=len(stack)-1
stack.append(item)
print("Elements in the stack are: ")
print("pushed item: " + item)
for i in range(top,-1,-1):
print (str(stack[i]))
Implementation and Use of python: Polish Notation
• Infix: The mathematical form of expression that we use generally is known as infix
notation. In infix form, an operator is written in between two operands.
• For example: An expression in the form of A * ( B + C ) / D is in infix form.
• Prefix: In prefix expression, an operator is written before its operands. This
notation is also known as “Polish notation”.
• For example, The above expression can be written in the prefix form as / * A + B C
D. This type of expression cannot be simply decoded as infix expressions.
• Postfix: In postfix expression, an operator is written after its operands. This
notation is also known as “Reverse Polish notation”.
• For example, The above expression can be written in the postfix form as A B C + *
Infix Expression: A+(B*C-(D/E^F)*G)*H, where ^ is an exponential operator.
Practice Questions
Q1. W A Python program to Input 10 integer number in List
and print in Ascending order without built-in function.
Q2. WA Python Program to Input 5 Student Name and print
total numbers of words in each name.
Q3. WA Python Function to accept elements list and print in
Last In First Out manner.
Pop Operation: Stack
implementation in python
# Removing an element from the stack: here stack is a list
def Pop(stack):
if (len(stack)==0):
return "stack is empty“
return stack.pop()
print("popped item: " + Pop(stack))
Practical Question
Q4. Write a program to implement a Stack for these book-details :
[Book No, Book Name]. That is now, each item node of the stack contains two
types of information – a book no. and its name. Just Implement PUSH(), POP()
and Display() operations.
Q5. Write a python function PUSH(Arr) where Arr is a list of numbers. From this
all the numbers divisible by 5 into a stack implemented by using List. Display the
stack if it has at least one element, otherwise display appropriate error.
Q6. Write a python function POP(Arr) where Arr is a list of numbers. The function
Q7. Amritya Seth is a programmer, who has recently been given a task to write a
python code to perform the following binary file operations with the help of two
user defined functions/modules:
a. AddStudents() to create a binary file called STUDENT.DAT containing student
information – roll number, name and marks (out of 100) of each student.
b. GetStudents() to display the name and percentage of those students who have
a percentage greater than 75. In case there is no student having percentage > 75
the function displays an appropriate message. The function should also display
the average percent.
Solution
Ans1.
stk=[]
def Disply(stk):
bkno=int(input(“Enter Book No.”))
bknm=input(“Enter Name of Book”)
if len(stk)==0:
itm=[bkno,bknm] print(‘Stack is Empty ‘)
def Push(stk,itm): else:
stk.append(itm) top=len(stk)-1
top =len(stk)-1
for i in range(len(top,-1,-1):
def Pop(stk): print(stk[i])
if(len(stk)==0):
print(“Stack is Empty”)
else:
print(stk.pop())
Using Python Libraries
• In the programming world, a library is a collection of precompiled
codes that can be used later on in a program for some specific well-
defined operations.
• A Python library is a collection of related modules. It contains
bundles of code that can be used repeatedly in different programs. It
makes Python Programming simpler and convenient for the
programmer.
• Python Library classified into following four categories: -
a. Framework ----- Multiple library
b. Library ------ Multiple packages
c. Package ------ Multiple module
d. Module ------ Multiple function/class
Python Library Hierarchy
How to import modules in Python?
Python module can be accessed in any of following way.
1. Python import statement
import math
print(“2 to the power 3 is ", math.pow(2,3))
Just similar to math ,user defined module can be accessed using import statement
2. Import with renaming
import math as mt
print(“2 to the power 3 is ", mt.pow(2,3))
3. Python from...import statement
from math import pow
print(“2 to the power 3 is ", pow(2,3))
4. Import all names
from math import *
print(“2 to the power 3 is ", pow(2,3))
How to create Module?
Using Module -It is a file which contains python functions/global
variables/classes etc. It is just .py file which has python executable code
/statement.
For example: Let’s create a file usermodule.py
def hello_message(user_name):
return “Hello " + name
Now we can import usermodule.py module by using import keyword
import <usermodule>
print usermodule.hello_message(“India")
How to Create Package?
It is namespace that contains multiple package or modules. It is a directory which contains a special
file “__ init __.py “
Let’s create a directory geometry. Now this package contains multiple packages / modules to handle
user related requests.
geometry/ # top level package
__ init __.py
rectangle/ # first subpackage
__ init __.py
area_rect.py
perimeter_rect.py
circle/ # second subpackage
__ init __.py
area_circ.py
perimeter_circ.py
Now we can import it in following way in other .py file
from geometry.rectangle import area_rect
from geometry.circle import perimeter_circ
How to Create Library?
The following directory and files structure to learn library creation & use
Define a function moduletest2() in module2.py file and call this function in
mylibcall.py file as a part of library1 library.
Now run mylibcall.py file
It will call moduletest2() method and display-’from module2’ message.
Please make sure that a blank file with __init__.py is created.
Using Framework
Framework is like a collection of various libraries which architects some more
component.
For e.g. Django which has various in-built libraries like Auth, user, database
connector etc.
Home Work Questions
Q1. Write a program to input two student’s data and write in a stack “stk”. Stack structure is as
under [Rollno, Name, Class, Percentage]
Q2. Write a program to show the detail of the student who scored the highest marks. Data stored
in “Data.csv” is given below :
Rollno, Name, Marks
1, Aman, 35
2, Kanak, 1
3, Anuj, 33
4, Suman, 25
Q3. Identify the missing part in the code to write the list object in the file
>>> import pickle
>>> x=[1,3,5,7]
>>> f=open('w.dat','wb')
>>> pickle._____(x,f)
>>> f.close()