Python Notes Class Xii Cs 083
Python Notes Class Xii Cs 083
com/
CLASS-XII
SUBJECT: COMPUTER SCIENCE (083) – PYTHON
INDEX
CHAPTER PAGE
CHAPTER NAME
NO. NO.
1 FUNCTIONS IN PYTHON 2
2 RECURSION 10
3 FILE HANDLING 13
5 PROGRAM EFFICIENCY 28
https://pythonschoolkvs.wordpress.com/ Page 1
CHAPTER-1
FUNCTIONS IN PYTHON
1.1 Definition: Functions are the subprograms that perform specific task. Functions are the
small modules.
Built in functions
Functions defined in
Types of functions modules
1. Library Functions: These functions are already built in the python library.
3. User Defined Functions: The functions those are defined by the user are called user
defined functions.
https://pythonschoolkvs.wordpress.com/ Page 2
2. Functions defined in modules:
a. Functions of math module:
To work with the functions of math module, we must import math module in program.
import math
S. No. Function Description Example
1 sqrt( ) Returns the square root of a number >>>math.sqrt(49)
7.0
2 ceil( ) Returns the upper integer >>>math.ceil(81.3)
82
3 floor( ) Returns the lower integer >>>math.floor(81.3)
81
4 pow( ) Calculate the power of a number >>>math.pow(2,3)
8.0
5 fabs( ) Returns the absolute value of a number >>>math.fabs(-5.6)
5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>math.exp(3)
20.085536923187668
Example:
import random
n=random.randint(3,7)
https://pythonschoolkvs.wordpress.com/ Page 3
Where:
Example:
def display(name):
https://pythonschoolkvs.wordpress.com/ Page 4
1.4 Calling the function:
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.
Syntax:
function-name(parameter)
Example:
ADD(10,20)
OUTPUT:
Sum = 30.0
def functionName(parameter):
… .. …
… .. …
… .. …
… .. …
functionName(parameter)
… .. …
… .. …
OUTPUT:
(7, 7, 11)
Example-3: Storing the returned values separately:
def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately
print(s1, s2, s3)
OUTPUT:
7 7 11
b. Function not returning any value (void function) : The function that performs some
operationsbut does not return any value, called void function.
def message():
print("Hello")
m=message()
print(m)
https://pythonschoolkvs.wordpress.com/ Page 6
OUTPUT:
Hello
None
Scope of a variable is the portion of a program where the variable is recognized. Parameters
and variables defined inside a function is not visible from outside. Hence, they have a local
scope.
1. Local Scope
2. Global Scope
1. Local Scope: Variable used inside the function. It can not be accessed outside the function.
In this scope, The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember the
value of a variable from its previous calls.
2. Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of a
variable is the period throughout which the variable exits in the memory.
Example:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
OUTPUT:
https://pythonschoolkvs.wordpress.com/ Page 7
Here, we can see that the value of x is 20 initially. Even though the function my_func()changed
the value of x to 10, it did not affect the value outside the function.
This is because the variable x inside the function is different (local to the function) from the
one outside. Although they have same names, they are two different variables with different
scope.
On the other hand, variables outside of the function are visible from inside. They have a global
scope.
We can read these values from inside the function but cannot change (write) them. In order to
modify the value of variables outside the function, they must be declared as global variables
using the keyword global.
https://pythonschoolkvs.wordpress.com/ Page 9
CHAPTER-2
RECURSION
2.1 Definition: A function calls itself, is called recursion.
2.2 Python program to find the factorial of a number using recursion:
Program:
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
https://pythonschoolkvs.wordpress.com/ Page 10
return(fibonacci(n-1)+fibonacci(n-2))
OUTPUT:
How many terms you want to display: 8
0 1 1 2 3 5 8 13
https://pythonschoolkvs.wordpress.com/ Page 11
Program:
def Binary_Search(sequence, item, LB, UB):
if LB>UB:
return -5 # return any negative value
mid=int((LB+UB)/2)
if item==sequence[mid]:
return mid
elif item<sequence[mid]:
UB=mid-1
return Binary_Search(sequence, item, LB, UB)
else:
LB=mid+1
return Binary_Search(sequence, item, LB, UB)
https://pythonschoolkvs.wordpress.com/ Page 12
CHAPTER-3
FILE HANDLING
3.1 INTRODUCTION:
File:- A file is a collection of related data stored in a particular area on the disk.
Stream: - It refers to a sequence of bytes.
File handling is an important part of any web application.
S.
Text Files Binary Files
No.
Example:
To open a file for reading it is enough to specify the name of the file:
f = open("book.txt")
The code above is the same as:
f = open("book.txt", "rt")
Where "r" for read mode, and "t" for text are the default values, you do not need to specify
them.
Text Binary
file File Description
mode Mode
‘r’ ‘rb’ Read - Default value. Opens a file for reading, error if the file does not
exist.
‘w’ ‘wb’ Write - Opens a file for writing, creates the file if it does not exist
‘a’ ‘ab’ Append - Opens a file for appending, creates the file if it does not exist
‘r+’ ‘rb+’ Read and Write-File must exist, otherwise error is raised.
‘x’ ‘xb’ Create - Creates the specified file, returns an error if the file exists
https://pythonschoolkvs.wordpress.com/ Page 14
In addition you can specify if the file should be handled as binary or text mode
“t” – Text-Default value. Text mode
“b” – Binary- Binary Mode (e.g. images)
Print/Access data
https://pythonschoolkvs.wordpress.com/ Page 15
Let a text file “Book.txt” has the following text:
“Python is interactive language. It is case sensitive language.
It makes the difference between uppercase and lowercase letters.
It is official language of google.”
OUTPUT: OUTPUT:
Python is interactive language. It is case sensitive Python is
language.
It makes the difference between uppercase and
lowercase letters.
It is official language of google.
https://pythonschoolkvs.wordpress.com/ Page 16
Some important programs related to read data from text files:
Program-a: Count the number of characters from a file. (Don’t count white spaces)
fin=open("Book.txt",'r')
str=fin.read()
L=str.split()
count_char=0
for i in L:
count_char=count_char+len(i)
print(count_char)
fin.close( )
fin=open("D:\\python programs\\Book.txt",'r')
str=fin.read()
L=str.split()
count=0
for i in L:
if i=='is':
count=count+1
print(count)
fin.close( )
To write the data to an existing file, you have to use the following mode:
https://pythonschoolkvs.wordpress.com/ Page 18
Example: Open the file "Book.txt" and append content to the file:
fout= open("Book.txt", "a")
fout.write("Welcome to the world of programmers")
Example: Open the file "Book.txt" and overwrite the content:
fout = open("Book.txt", "w")
fout.write("It is creative and innovative")
Program: Write a program to take the details of book from the user and write the record
in text file.
fout=open("D:\\python programs\\Book.txt",'w')
n=int(input("How many records you want to write in a file ? :"))
for i in range(n):
print("Enter details of record :", i+1)
title=input("Enter the title of book : ")
price=float(input("Enter price of the book: "))
record=title+" , "+str(price)+'\n'
fout.write(record)
fout.close( )
OUTPUT:
How many records you want to write in a file ? :3
Enter details of record : 1
Enter the title of book : java
Enter price of the book: 250
Enter details of record : 2
Enter the title of book : c++
Enter price of the book: 300
Enter details of record : 3
Enter the title of book : python
Enter price of the book: 450
https://pythonschoolkvs.wordpress.com/ Page 19
"a" - Append - will append to the end of the file.
Program: Write a program to take the details of book from the user and write the record
in the end of the text file.
fout=open("D:\\python programs\\Book.txt",'a')
n=int(input("How many records you want to write in a file ? :"))
for i in range(n):
print("Enter details of record :", i+1)
title=input("Enter the title of book : ")
price=float(input("Enter price of the book: "))
record=title+" , "+str(price)+'\n'
fout.write(record)
fout.close( )
OUTPUT:
How many records you want to write in a file ? :2
Enter details of record : 1
Enter the title of book : DBMS
Enter price of the book: 350
Enter details of record : 2
Enter the title of book : Computer
Networking
Enter price of the book: 360
d. Delete a file: To delete a file, you have to import the os module, and use remove( )
function.
import os
os.remove("Book.txt")
https://pythonschoolkvs.wordpress.com/ Page 20
import os
if os.path.exists("Book.txt"):
os.remove("Book.txt")
else:
print("The file does not exist")
Output:
https://pythonschoolkvs.wordpress.com/ Page 21
Output:
Once upon a time
Output:
14
Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
fout.seek(5)
print(fout.tell( ))
fout.close( )
Output:
5
3.8 File I/O Attributes
Attribute Description
name Returns the name of the file (Including path)
mode Returns mode of the file. (r or w etc.)
encoding Returns the encoding format of the file
closed Returns True if the file closed else returns False
https://pythonschoolkvs.wordpress.com/ Page 22
Example:
f = open("D:\\story.txt", "r")
print("Name of the File: ", f.name)
print("File-Mode : ", f.mode)
print("File encoding format : ", f.encoding)
print("Is File closed? ", f.closed)
f.close()
print("Is File closed? ", f.closed)
OUTPUT:
Name of the File: D:\story.txt
File-Mode : r
File encoding format : cp1252
Is File closed? False
Is File closed? True
https://pythonschoolkvs.wordpress.com/ Page 23
CHAPTER-4
CREATE & IMPORT PYTHON LIBRARIES
4.1 INTRODUCTION:
Python has its in-built libraries and packages. A user can directly import the libraries and its
modules using import keyword. If a user wants to create libraries in python, he/she can create
and import libraries in python.
Example:
Let’s create a package named Shape and build three modules in it namely Rect, Sq and Tri to
calculate the area for the shapes rectangle, square and triangle.
Step-1 First create a directory and name it Shape. ( In this case it is created under
C:\Users\ViNi\AppData\Local\Programs\Python\Python37-32\ directory path.)
Step-2 Create the modules in Shape directory.
To create Module-1(Rect.py), a file with the name Rect.py and write the code in it.
class Rectangle:
def __init__(self):
print("Rectangle")
https://pythonschoolkvs.wordpress.com/ Page 24
To create Module-2(Sq.py), a file with the name Sq.py and write the code in it.
class Square:
def __init__(self):
print("Square")
def Area(self, side):
self.a=side
print("Area of square is : ", self.a*self.a)
To create Module-3 (Tri.py), a file with the name Tri.py and write the code in it.
class Triangle:
def __init__(self):
print("Trinagle")
Step-3 Create the __init__.py file. This file will be placed inside Shape directory and can be
left blank or we can put this initialisation code into it.
from Shape import Rect
from Shape import Sq
from Shape import Tri
That’s all. Package created. Name of the package is Shape and it has three modules namely
Rect, Sq and Tri.
https://pythonschoolkvs.wordpress.com/ Page 25
from Shape import Rect
from Shape import Sq
from Shape import Tri
OUTPUT:
Rectangle
Area of Rectangle is : 200
Square
Area of square is : 100
Trinagle
Area of Triangle is : 24.0
https://pythonschoolkvs.wordpress.com/ Page 26
r=Shape.Rect.Rectangle( )
s=Shape.Sq.Square( )
t=Shape.Tri.Triangle( )
Method-2:
If we want to access a specific module of a package then we can use from and import
keywords.
Syntax:
from package-name import module-name
Example:
from Shape import Rect
r=Rect.Rectangle( )
s=Sq.Square( )
t=Tri.Triangle( )
Method-3:
If a user wants to import all the modules of Shape package then he/she can use * (asterisk).
Example:
from Shape import *
r=Rect.Rectangle( )
s=Sq.Square( )
t=Tri.Triangle( )
https://pythonschoolkvs.wordpress.com/ Page 27
CHAPTER-5
PROGRAM EFFICIENCY
5.1 INTRODUCTION:
Program efficiency is a property of a program related to time taken by a program for execution
and space used by the program. It is also related to number of inputs taken by a program.
Complexity: To measure the efficiency of an algorithm or program in terms of space and time.
The program which uses minimum number of resources, less space and minimum time, is
known as good program.
Complexity
Time and space complexity depends on lots of things like hardware, operating system,
processors, size of inputs etc.
Best case: The minimum number of steps that an algorithm can take for any input data
values.
Average case: The efficiency averaged on all possible inputs. We normally assume the
uniform distribution.
Worst case: The minimum number of steps that an algorithm can take for any input data
values.
https://pythonschoolkvs.wordpress.com/ Page 28
5.2 Estimation the complexity of a program:
Suppose you are given a list L and a value x and you have to find if x exists in List L.
Simple solution to this problem is traverse the whole List L and check if the any element is
equal to x.
Each of the operation in computer take approximately constant time. Let each operation
takes t time. The number of lines of code executed is actually depends on the value of x.
During analysis of algorithm, mostly we will consider worst case scenario, i.e., when x is not
present in the list L. In the worst case, the if condition will run n times where n is the length of
the list L. So in the worst case, total execution time will be (n∗t+t). n∗t for the if condition
and t for the return statement.
As we can see that the total time depends on the length of the list L. If the length of the list will
increase the time of execution will also increase.
Order of growth is how the time of execution depends on the length of the input.
In the above example, we can clearly see that the time of execution is linearly depends on the
length of the list.
Order of growth in algorithm means how the time for computation increases when you increase
the input size. It really matters when your input size is very large.
For example, a process requiring n2 steps and another process requiring 1000n2 steps and
another process requiring 3n2+10n+17 steps. All have O(n2) order of growth. Order of growth
provides a useful indication of how we may expect the behavior of the process to change as we
change the size of the problem. Depending on the algorithm, the behaviour changes. So, this is
one of the most important things that we have to care when we design an algorithm for some
given problem.
https://pythonschoolkvs.wordpress.com/ Page 29
There are different notations to measure it and the most important one is Big O notation which
gives you the worst case time complexity.
for i in range(1, num + 1): print("factorial does not exist for negative numbers")
factorial = factorial*i elif num==0:
https://pythonschoolkvs.wordpress.com/ Page 30
else:
end=time.time() print("The factorial of ",num," is ", factorial(num))
t=end-start end=time.time( )
OUTPUT: OUTPUT:
Enter a number: 5 enter the number: 5
Recursive program is taking less time than without recursion program. So, Program with
recursion is efficient. Therefore, we can conclude that Performance of algorithm is inversely
proportional to the wall clock time.
https://pythonschoolkvs.wordpress.com/ Page 31
CHAPTER-6
DATA VISUALIZATION USING PYPLOT
6.1 NTRODUCTION:
Data visualization basically refers to the graphical or visual representation of information and
data using charts, graphs, maps etc.
pyplot is an interface, which exists in matplotlib library.
To draw the lines, charts etc. first of all we have to install matplotlib library in our
computer and import it in the python program.
matplotlib is a package which is used to draw 2-D graphics.
Program:
import matplotlib.pyplot as pl #pl is alias for matplot.pyplot
x=[2, 8] # values of x1 and x2
y=[5, 10] #values of y1 and y2
pl.plot(x,y) # to create a line
https://pythonschoolkvs.wordpress.com/ Page 32
pl.xlabel("Time") #label name for x-axis
pl.ylabel("Distance") #label name for y-axis
pl.show() #to show the line
Output:
color code
Red ‘r’
Green ‘g’
https://pythonschoolkvs.wordpress.com/ Page 33
Blue ‘b’
Yellow ‘y’
Magenta ‘m’
Black ‘k’
Cyan ‘c’
White ‘w’
Line width:
Syntax:
matplotlib.pyplot.plot(data1, data2, linewidth=value)
Example:
matplotlib.pyplot.plot(x, y, ‘c’, linewidth=6)
Line style:
Syntax:
matplotlib.pyplot.plot(data1, data2, linestyle = value)
Example:
matplotlib.pyplot.plot(x, y, ‘:’)
https://pythonschoolkvs.wordpress.com/ Page 34
Different types of line styles:
-. Dash-dot line
https://pythonschoolkvs.wordpress.com/ Page 35
Some marker types for plotting:
Note: color of the line and marker type can be written combined e.g. ‘ro’ means red color of
the line with circle marker. If you don’t specify the linestyle separately along with linecolor
and marker type combination. Example:
with combination of line color and marker type with combination of line color, marker type along
with linestyle
https://pythonschoolkvs.wordpress.com/ Page 36
6.2.2 Bar Chart:
A bar chart is a graphical display of data using bars of different heights.
import the matplotlib library and pyplot interface.
pyplot interface has bar( ) function to create a bar chart.
To set the lables for x-axis and y-axis, xlabel( ) and ylabel( ) functions are used.
Use show( ) function to display the bar chart.
There are two types of bar charts:
1. Single bar chart
2. Multiple bar chart
OUTPUT:
https://pythonschoolkvs.wordpress.com/ Page 37
The bar( ) function has width argument to set the width of all bars. It has color argument also,
to change the color of bars.
https://pythonschoolkvs.wordpress.com/ Page 38
2. Multiple Bar Charts:
Program:
import matplotlib.pyplot as pl
import numpy as np # importing numeric python for arange( )
boy=[28,45,10,30]
girl=[14,20,36,50]
X=np.arange(4) # creates a list of 4 values [0,1,2,3]
pl.bar(X, boy, width=0.2, color='r', label="boys")
pl.bar(X+0.2, girl, width=0.2,color='b',label="girls")
pl.legend(loc="upper left") # color or mark linked to specific data range plotted at location
pl.title("Admissions per week") # title of the chart
pl.xlabel("week")
pl.ylabel("admissions")
pl.show( )
OUTPUT:
https://pythonschoolkvs.wordpress.com/ Page 39
Syntax for legend( ):
matplotlib.pyplot.legend(loc= ‘postion-number or string’)
Example:
matplotlib.pyplot.legend(loc= ‘upper left’)
OR
matplotlib.pyplot.legend(loc= 2)
upper right 1
upper left 2
lower left 3
lower right 4
center 10
Example:
import matplotlib.pyplot as pl
part=[12,9,69,10]
pl.pie(part)
pl.show( )
https://pythonschoolkvs.wordpress.com/ Page 40
Add Labels to slices of pie chart:
To display labels of pie chart, pie( ) function has labels argument.
Example:
import matplotlib.pyplot as pl
part=[12,9,69,10]
pl.pie(part, labels=['abc','pqr','xyz','def'])
pl.show( )
OUTPUT:
https://pythonschoolkvs.wordpress.com/ Page 41
autopct argument calculates automatic percentage for each share.
autopct argument has a formatted string as a value. Example : %1.1f%%
Syntax for formatted string is:
%<flag><width> . <precision><type>% %
o % symbol: In the starting and ending, the % symbol specifies that it is a special
formatted string. One more % after the type is to print a percentage sign after
value.
o flag: if digits of value are less than width, then flag is preceded to value.
o width: Total number of digits to be displayed (including the digits after decimal
point). If the value has more digits than the width specifies, then the full value is
displayed.
o precision: Number of digits to be displayed after decimal point.
o type: Specifies the type of value. f or F means float type value, d or i means
integer type value.
Example:
%07.2f%%
Where
% = starting and ending % specifies that it is a special formatted string
0= flag
7=width
2= digits after decimal point
f=float type
%= percentage sign to be displayed after value
https://pythonschoolkvs.wordpress.com/ Page 42
then percentage of first share:
= (12*100)/(12+25+10+32)
= 1200/79
=15.19
OUTPUT:
Exploding a slice:
Add explode argument to pie( ) function.
Example:
import matplotlib.pyplot as pl
part=[12,9,69,10]
clr=['g','m','y','c']
ex=[0, 0.2, 0, 0] # exploding 2nd slice with the distance 0.2 units
https://pythonschoolkvs.wordpress.com/ Page 43
pl.pie(part, colors=clr, labels=['abc','pqr','xyz','def'], autopct='%1.1f%%', explode=ex)
pl.show( )
OUTPUT:
https://pythonschoolkvs.wordpress.com/ Page 44
CHAPTER-7
DATA STRUCTURE-I (LINEAR LIST)
7.1 INTRODUCTION:
Definition: The logical or mathematical model of a particular organization of data is called
data structure. It is a way of storing, accessing, manipulating data.
DATA STRUCTURE
LINKED
ARRAY STACK QUEUE TREE GRAPH
LIST
1. Linear data structure: It is simple data structure. The elements in this data structure creates
a sequence. Example: Array, linked list, stack, queue.
2. Non-Linear data structure: The data is not in sequential form. These are multilevel data
structures. Example: Tree, graph.
https://pythonschoolkvs.wordpress.com/ Page 45
7.3 OPERATION ON DATA STRUCTURE:
There are various types of operations can be performed with data structure:
1. Traversing: Accessing each record exactly once.
2. Insertion: Adding a new element to the structure.
3. Deletion: Removing element from the structure.
4. Searching: Search the element in a structure.
5. Sorting: Arrange the elements in ascending and descending order.
6. Merging: Joining two data structures of same type. (not covered in syllabus)
Output:
10
20
30
40
50
b. Inserting Element in a list: There are two ways to insert an element in a list:
(i) If the array is not sorted
(ii) If the array is sorted
https://pythonschoolkvs.wordpress.com/ Page 46
(i) If the array is not sorted: In this case, enter the element at any position using insert( )
function or add the element in the last of the array using append( ) function.
Example:
L=[15,8,25,45,13,19]
L.insert(3, 88) # insert element at the index 3
print(L)
Output:
[15, 8, 25, 88, 45, 13, 19]
(ii) If the array is sorted: In this case, import bisect module and use the functions bisect( ) and
insort( ).
bisect( ) : identifies the correct index for the element and returns the index.
insort( ): Inserts the element in the list in its correct order.
Example:
import bisect
L=[10,20,30,40,50]
print("Array before insertion the element:", L)
item=int(input("Enter the element to insert in array: "))
pos=bisect.bisect(L,item) #will return the correct index for item
bisect.insort(L,item) #will insert the element
print("Element inserted at index: ", pos)
print("Array after insertion the element : ", L)
OUTPUT:
Array before insertion the value: [10, 20, 30, 40, 50]
Enter the element to insert in array: 35
Element inserted at index : 3
Array after insertion the element : [10, 20, 30, 35, 40, 50]
Note: bisect( ) works only with that lists which are arranged in ascending order.
https://pythonschoolkvs.wordpress.com/ Page 47
c. Deletion of an element from a List: To delete an element from a list we can use remove( )
or pop( ) method.
Example:
L=[10,15,35,12,38,74,12]
print("List Before deletion of element: ", L)
val=int(input("Enter the element that you want to delete: "))
L.remove(val)
print("After deletion the element", val,"the list is: ", L)
OUTPUT:
List Before deletion of element: [10, 15, 35, 12, 38, 74, 12]
Enter the element that you want to delete: 12
After deletion the element 12 the list is: [10, 15, 35, 38, 74, 12]
d. Searching in a List:
There are two types of searching techniques we can use to search an element in a list. These
are:
(i) Linear Search
(ii) Binary Search
https://pythonschoolkvs.wordpress.com/ Page 48
break
else:
print("Element not Found")
Output:
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4
https://pythonschoolkvs.wordpress.com/ Page 49
if found>=0:
print(element, "Found at the position : ",found+1)
else:
print("Element not present in the list")
OUTPUT:
Enter the elements in sorted order: [12,23,31,48,51,61,74,85]
Enter the element that you want to search : 61
61 Found at the position : 6
e. Sorting: To arrange the elements in ascending or descending order. There are many sorting
techniques. Here we shall discuss two sorting techniques:
(i) Bubble sort
(ii) Insertion sort
(i) BUBBLE SORT: Bubble sort is a simple sorting algorithm. It is based on comparisons, in
which each element is compared to its adjacent element and the elements are swapped if they
are not in proper order.
https://pythonschoolkvs.wordpress.com/ Page 50
PROGRAM:
n=len(L)
for p in range(0,n-1):
for i in range(0,n-1):
if L[i]>L[i+1]:
OUTPUT:
The sorted list is : [8, 12, 24, 45, 60, 77, 87, 90]
https://pythonschoolkvs.wordpress.com/ Page 51
(ii) INSERTION SORT: Sorts the elements by shifting them one by one and inserting the
element at right position.
PROGRAM:
n=len(L)
for j in range(1,n):
temp=L[j]
prev=j-1
prev=prev-1
Enter the elements: [45, 11, 78, 2, 56, 34, 90, 19]
The sorted list is : [2, 11, 19, 34, 45, 56, 78, 90]
7.4.2. Multi-Dimensional array (Nested Lists): A list can also hold another list as its element.
It is known as multi-dimensional or nested list.
A list in another list considered as an element.
Example:
>>>NL=[10, 20, [30,40], [50,60,70], 80]
>>> len(NL)
5
>>>secondlist=[1,2,3,[4,5,[6,7,8],9],10,11]
>>> len(secondlist)
6
Example-2:
>>> L=["Python", "is", "a", ["modern", "programming"], "language", "that", "we", "use"]
>>> L[0][0]
'P'
>>> L[3][0][2]
'd'
>>> L[3:4][0]
['modern', 'programming']
>>> L[3:4][0][1]
'programming'
>>> L[3:4][0][1][3]
'g'
>>> L[0:9][0]
'Python'
>>> L[0:9][0][3]
'h'
>>> L[3:4][1]
IndexError: list index out of range
https://pythonschoolkvs.wordpress.com/ Page 54
CHAPTER-8
DATA STRUCTURE-II (STACK AND QUEUE)
8.1 STACK IN PYTHON:
8.1.1 INTRODUCTION:
Stack is a linear data structure.
Stack is a list of elements in which an element may be inserted or deleted only at one
end, called the TOP of the stack.
It follows the principle Last In First Out (LIFO).
There are two basic operations associated with stack:
o Push : Insert the element in stack
o Pop : Delete the element from stack
def size(self): # Size of the stack i.e. total no. of elements in stack
return len(self.items)
s = Stack( )
print("MENU BASED STACK")
cd=True
while cd:
print(" 1. Push ")
print(" 2. Pop ")
print(" 3. Display ")
print(" 4. Size of Stack ")
print(" 5. Value at Top ")
if choice==1:
val=input("Enter the element: ")
s.push(val)
elif choice==2:
if s.items==[ ]:
print("Stack is empty")
else:
print("Deleted element is :", s.pop( ))
elif choice==3:
print(s.items)
elif choice==4:
print("Size of the stack is :", s.size( ))
elif choice==5:
print("Value of top element is :", s.peek( ))
else:
print("You enetered wrong choice ")
https://pythonschoolkvs.wordpress.com/ Page 56
print("Do you want to continue? Y/N")
option=input( )
if option=='y' or option=='Y':
var=True
else:
var=False
Exponentiation ↑ 1
https://pythonschoolkvs.wordpress.com/ Page 57
Element Operation Stack Result
5 Push 5
6 Push 5, 6
2 Push 5, 6, 2
+ Pop 5, 8 6+2=8
* Pop 40 5*8=40
12 Push 40, 12
4 Push 40, 12, 4
/ Pop 40, 3 12/4=3
- Pop 37 40-3=37
https://pythonschoolkvs.wordpress.com/ Page 58
8.1.5 Infix to Postfix Conversion:
Example-1 : Convert the following infix expression into its equivalent postfix expression.
Y= ( A + B * ( C-D ) / E )
Symbol Stack Expression Description
( ( Push the symbol in stack
A ( A Move the element in expression
+ (+ A Operator, so push into stack
B (+ AB Move the element in expression
* (+* AB Operator, push into stack, * has higher precedence than
+, so can come after +
( (+*( AB Push the open parentheses symbol into stack
C (+*( ABC Move the element in expression
- (+*(- ABC Operator, push into stack
D (+*(- ABCD Move the element in expression
) (+* ABCD - Closing parentheses, so pop the elements of the stack up
to opening parentheses
/ (+/ ABCD - * Operator, / and * operators have the same precedence,
so associativity from left to write will take place and *
will pop from stack and / will push into stack
E (+/ ABCD - *E Move the element in expression
) ABCD - * E / + Closing parentheses, so pop the elements of the stack up
to opening parentheses
Example-2 : Convert the following infix expression into its equivalent postfix expression.
Y= ( A / B - ( C*D ↑ E ) + F )
Symbol Stack Expression Description
( ( Push the symbol in stack
A ( A Move the element into expression
/ (/ A Operator, so push into stack
B (/ AB Move the element into expression
- (- AB/ Operator, - has lower precedence than /. so, / will pop
from stack and – will push into stack.
( (-( AB/ Push the symbol into stack
C (-( AB/C Move the element into expression
* (-(* AB/C Operator, push into stack
D (-(* AB/CD Move the element into expression
↑ ( - ( *↑ AB/CD Operator, ↑ has higher precedence than *, so can come
after *.
E ( - ( *↑ AB/CDE Move the element into expression
https://pythonschoolkvs.wordpress.com/ Page 59
) (- AB/CDE↑ * Closing parentheses, so pop the elements of the stack up
to opening parentheses
+ (+ AB/CDE↑ * - Operator, - and + both have same precedence, to
associativity from left to right take place. – will pop
from stack then + will push into stack.
F (+ AB/CDE↑ * - F Move the element into expression
Remove Insert
10 20 30 40 50 60
front rear
8.2.2 MENU BASED PROGRAMME FOR QUEUE:
class Queue:
def __init__(Q):
Q.items = [ ]
https://pythonschoolkvs.wordpress.com/ Page 60
Q.items.append(item)
if len(Q.items)==1:
front=rear=0
else:
rear=len(Q.items)
def size(Q): # Size of the queue i.e. total no. of elements in queue
return len(Q.items)
q = Queue( )
print("MENU BASED QUEUE")
cd=True
while cd:
print(" 1. ENQUEUE ")
print(" 2. DEQUEUE ")
print(" 3. Display ")
print(" 4. Size of Queue ")
print(" 5. Value at rear ")
https://pythonschoolkvs.wordpress.com/ Page 61
if choice==1:
val=input("Enter the element: ")
q.Enqueue(val)
elif choice==2:
if q.items==[ ]:
print("Queue is empty")
else:
print("Deleted element is :", q.Dequeue( ))
elif choice==3:
print(q.items)
elif choice==4:
print("Size of the queue is :", q.size( ))
elif choice==5:
print("Value of rear element is :", q.peek( ))
else:
print("You entered wrong choice ")
https://pythonschoolkvs.wordpress.com/ Page 62
A Circular Queue can be seen as an improvement over the Linear Queue because:
1. There is no need to reset front and rear, since they reset themselves. This means that
once the front or rear reaches the end of the Queue, it resets itself to 0.
2. The rear and front can point to the same location - this means the Queue is empty.
Job Scheduling
Traffic Signals
https://pythonschoolkvs.wordpress.com/ Page 63
CQ.rear = (CQ.rear + 1) % CQ.maxSize
q = CircularQueue()
print("MENU BASED CIRCULAR QUEUE")
cd=True
while cd:
print("1. ENQUEUE")
print("2. DEQUEUE")
print("3. DISPLAY ")
print("4. Front Position ")
print("5. Rear Position ")
choice=int(input("Enter your choice (1-5) : "))
if choice==1:
val=input("Enter the element: ")
q.C_enqueue(val)
elif choice==2:
q.C_dequeue()
elif choice==3:
print(q.queue)
elif choice==4:
print("Front element position :", q.front)
elif choice==5:
print("Rear element position : ", q.rear)
https://pythonschoolkvs.wordpress.com/ Page 64
else:
print("You entered invalid choice: ")
https://pythonschoolkvs.wordpress.com/ Page 65