0% found this document useful (0 votes)
81 views51 pages

It Workshop

The document provides information about a lab manual for the course 18CS5SP08L IT Workshop (Python). It includes the institute and department visions and missions, program educational objectives, program specific outcomes, program outcomes, and mapping of outcomes to objectives and competencies. It also lists the course outcomes, maps the course outcomes to program outcomes, and provides a list of experiments with their associated course outcomes. The document outlines the contents of the lab manual for a Python programming course.

Uploaded by

Sarthak Dugar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views51 pages

It Workshop

The document provides information about a lab manual for the course 18CS5SP08L IT Workshop (Python). It includes the institute and department visions and missions, program educational objectives, program specific outcomes, program outcomes, and mapping of outcomes to objectives and competencies. It also lists the course outcomes, maps the course outcomes to program outcomes, and provides a list of experiments with their associated course outcomes. The document outlines the contents of the lab manual for a Python programming course.

Uploaded by

Sarthak Dugar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Bachelor of Technology

in
Computer Science and Engineering

Lab Manual
For
18CS5SP08L
IT Workshop (Python)

Faculty of Engineering & Technology


Global Campus
45th km NH – 209, Jakkasandra Post, Kanakapura Rd, Bangalore
www.set.jainuniversity.ac.in
Fax STD Code:- 080 Fax:-  2757 7199

1
CONTENTS

# TITLE PAGE NO.

1. Institute Vision and Mission 3

2. Department Vision and Mission 3

3. PEOs 4

4. Program Specific Outcomes (PSO) 4

5. Program Outcomes (PO) 4

6. Mapping of PEOs and POs 5

7. Course Outcome (CO) Statements and CO-PO Mapping 6

8. List of experiment with CO Mapping 7

9. List of Tools used and Ref books

Aim, Description, Algorithms, Program and Output of


10.
each experiment
Rubrics for Evaluation ( CIA and Semester End
11.
Assessment)

Faculty in-charge(s) Head of the Department

2
Institute Vision and Mission

Vision:
To be a leading technical institution that offers a transformative education to create leaders and
innovators with ethical values to contribute for the sustainable development and economic growth of our
nation.

Mission:
M1: To impart high standard of engineering education through innovative teaching and research to meet
the changing needs of the modern society.
M2: To provide outcome-based education that transforms the students to understand and solve the
societal, industrial problems through engineering and technology.
M3: To collaborate with other leading technical institutions and organization to develop globally
competitive technocrats and entrepreneurs.

Department Vision and Mission

Vision:
To emerge as a model center for education and research in the area of Computer Science and
Engineering through Knowledge acquisition, dissemination and generation to meet societal demands.

Mission:
M1: To impart the quality education in cutting edge technologies, teaching & learning ambience in
Computer Science and Engineering.
M2: To establish a center of excellence in collaboration with industries, research laboratories and other
agencies to meet the changing needs of society.
M3: To provide an environment conducive to develop innovation, team-spirit and Entrepreneurship.
M4: To practice and promote high standards of professional ethics and transparency.

3
Program Educational Objectives (PEOs)

Program Educational Objectives


Graduates of B. Tech in Computer Science and Engineering with specialization in IoT will be able to
PEO1: Build up requisite knowledge and skills to successfully take-up employment or research in their
domain.
PEO2: Critically analyze existing tools and techniques in Internet of Things and develop innovative and
research-oriented methodologies to analyze and solve the problems identified.
PEO3: Excel in professional career with enhancement in qualification through skills obtained.
PEO4: Serve the society with ethics, be responsible citizens and provide employment to others through
entrepreneurship.

Program Specific Outcomes (PSO)


During the graduation students should be able to:
PSO1: Ability to apply their skills in the field of Project management, Quality and cost management,
cultivating skills through higher studies and entrepreneurship.
PSO2: Ability to apply their skill in the field of new product Development, Cost Cutting and Improving
Existing Techniques through engagement in Post Graduate Programs study or engagement in Research and
Innovation.

Program Outcomes

Engineering Graduate’s attributes

Sl.No. Program Outcomes


Engineering knowledge: Apply the knowledge of mathematics, science, engineering
1. fundamentals, and an engineering specialization to the solution of complex
engineering problems.
Problem analysis: Identify, formulate, review research literature, and analyze
2. complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,

4
societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge and
4. research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and
5. modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to
6. assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional
7. engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities
8.
and norms of the engineering practice.
Individual and teamwork: Function effectively as an individual, and as a member or
9.
leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as, being able to
10.
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a
11.
member and leader in a team, to manage projects and in multidisciplinary
environments.
Life-long learning: Recognize the need for, and have the preparation and ability to
12. engage in independent and life-long learning in the broadest context of technological
change.

5
Course Outcome Statements and CO-PO Mapping

Course Outcome Statements


Understand the basics of Python Programming.
18CS5SP08L.1

Apply various data structures for solving real world problems.


18CS5SP08L.2

18CS5SP08L.3 Create basic data structure of given problem in python programming


Analyze the data transformation from one format to another format.
18CS5SP08L.4

Build Embedded system projects on Raspberry Pi using Python


18CS5SP08L.5

Develop Image Processing system on Raspberry Pi board


18CS5SP08L.6

CO – PO Mapping
CO/PO: Mapping
(H/M/L indicates strength of correlation) 3-High, 2-Medium, 1-Low
Course Programme Outcome (POs)
Outcome PO-9 PSO-2
PO-1 PO-2 PO-3 PO-4 PO-5 PO-6 PO-7 PO-8 PO-10 PO-11 PO-12 PSO-1
(COs)
CO-1 3 2 2 1 1 1 1
CO-2 3 2 2 1 1 1 1
CO-3 3 2 2 1 1 2 2
CO-4 3 2 2 2 1 1 2 2
CO-5 3 2 3 2 1 1 2 2
CO-6 3 2 3 2 1 1 2 2
Avg : 18 12 14 9 3 6 10 10

6
List of Experiment with CO Mapping

# Title of the Experiment CO


1. Write programs to implement the following operations: CO1
a. To elaborate variables and their data types such as int, float, boolean,
string, list, set,
dictionary and tuples; swap two numbers
b. To perform mathematical operations such as addition, subtraction,
multiplication,division, modulo, and power; also explore the operator
precedence.
2. Write programs to implement conditional operations on following: CO1
a. Python program to find the sum and average of natural numbers up to
n where n is provided by user.
b. Python program to find factorial, and Fibonacci of a number, received
by user, with iterative as well as recursive process.
3. Write python programs CO2
a. To print all prime numbers between N and M.
b. To find largest among three numbers, input by user.
c. To find GCD for two numbers, input by user
4. Write python program to elaborate string operations such as CO3
a) Implement a python script to check the element is in the list or not by
using linear search & Binary search.
b) Implement a python script to arrange the elements in sorted order
using Bubble, Selection, Insertion and Merge sorting techniques.
5. Write Python program CO2
a. Implement python script to show the usage of various operators
available in python language.
b. Write a program to calculate overtime pay of 10 employees. Overtime
is paid at the rate of Rs.12.00 per hour for every hour worked above 40
hours. Assume that employee do not work for fractional part of an hour.
6. Write Python program using NumPy and pandas CO4
a. Write a Pandas program to create and display a DataFrame from a
specified dictionary datawhich has the index labels.
b. To create a 4X2 integer array and prints its attributes.
c. For the given numpy array return array of odd rows and even
columns.
d. To add the two NumPy arrays and modify a result array by
calculating the square root ofeach element.
7. Write python program to show following plots using Matplotlib library.[ CO4
General case study]
a. To read total profit of all months and show it using a line plot where x
axis should bemonth number and y axis should be named as total profit.
b. To get total profit of all months and show line plot with the following
7
style properties
Line Style dotted and Line-color should be red
Show legend at the lower right location.
X label name = Month Number
Y label name = Sold units number
Add a circle marker.
Line marker color as read
Line width should be 3.
8. Write python programs for following graphical objects CO4
a. Draw the target symbol (a set of concentric squares, alternating red
and white) in agraphics window, that is, 200 pixels wide by 200 pixels
high. (Hint: Draw the targetsquare first in red, followed by next smaller
square in white, then draw the next smallersquare in red).
b. Create a 5x5 rectangle whose top left corner is at (row*5, col*5). If
the sum of the rowsand columns’ number is even, set the fill color of the
rectangle to white, otherwise set itto the black. Then draw the rectangle.
9. CO5
10. CO5
11. CO6
12. CO6

List of Tools used and Reference books

Tools / Software used


# Tools / Software Used Licensed / Open source
Pycharm Open source
1

Jupyter Notebook Open Source


2

Reference Text Books


1. Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming
Paperback – Illustrated, May 3, 2019 (Eric Matthes (Author) Visit Amazon's Eric Matthes
Page

8
2. Python (2nd Edition): Learn Python in One Day and Learn It Well. Python for Beginners
with Hands-on Project. (Learn Coding Fast with Hands-On Project Book 1) Kindle Edition
( by LCF Publishing (Author), Jamie Chan  (Author)  Format: Kindle Edition)

JUPYTER NOTEBOOK
Jupyter Notebook is an open-source web application that allows you to create and share documents
that contain live code, equations, visualizations, and narrative text. Uses include data cleaning and
transformation, numerical simulation, statistical modeling, data visualization, machine learning,
and much more.

Jupyter has support for over 40 different programming languages and Python is one of them.
Python is a requirement (Python 3.3 or greater, or Python 2.7) for installing the Jupyter Notebook
itself.

Jupyter Notebook can be installed by using either of the two ways described below:

Using Anaconda:
Install Python and Jupyter using the Anaconda Distribution, which includes Python, the Jupyter
Notebook, and other commonly used packages for scientific computing and data science. To install
Anaconda, go through How to install Anaconda on windows? and follow the instructions provided.
Using PIP:
Install Jupyter using the PIP package manager used to install and manage software
packages/libraries written in Python. To install pip, go through How to install PIP on Windows?
and follow the instructions provided.

Installing Jupyter Notebook using Anaconda:


Anaconda is an open-source software that contains Jupyter, spyder, etc that are used for large data
processing, data analytics, heavy scientific computing. Anaconda works for R and python
programming language. Spyder(sub-application of Anaconda) is used for python. Opencv for
python will work in spyder. Package versions are managed by the package management system
called conda.

To install Jupyter using Anaconda, just go through the following instructions:

9
Click on the Install Jupyter Notebook Button

10
Beginning the Installation:

Launching Jupyter:

11
Installing Jupyter Notebook using pip:
PIP is a package management system used to install and manage software packages/libraries
written in Python. These files are stored in a large “on-line repository” termed as Python Package
Index (PyPI).
pip uses PyPI as the default source for packages and their dependencies.

To install Jupyter using pip, we need to first check if pip is updated in our system. Use the
following command to update pip:
python -m pip install --upgrade pip

After updating the pip version, follow the instructions provided below to install Jupyter:
Command to install Jupyter:
python -m pip install jupyter
Beginning Installation:

12
Experiment -1
Write programs to implement the following operations:
A. To elaborate variables and their data types such as int, float, boolean, string, list, set, Dictionary and
tuples; swap two numbers.

Description:
Data types are the classification or categorization of data items. Data types represent a kind of
value which determines what operations can be performed on that data. Numeric, non-numeric and
Boolean (true/false) data are the most used data types. However, each programming language has
its own classification largely reflecting its programming philosophy.

Program:
Int, Float:
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))

Output:

Boolean:
print(type(True))
print(type(False))

Output:

String:
# Creating a String
# with single Quotes
String1 = 'Welcome to Jain University'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
13
# with double Quotes
String1 = "I'm souvik"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String
# with triple Quotes
String1 = '''I'm souvik.I study in Jain University'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
# Creating String with triple
# Quotes allows multiple lines
String1 = '''Jain
University'''
print("\nCreating a multiline String: ")
print(String1)

Output:

List:
# Creating a List
List = []
print("Intial blank List: ")
print(List)
# Creating a List with
# the use of a String
List = ['JainUniversity']
print("\nList with the use of String: ")
print(List)
# Creating a List with
# the use of multiple values
List = ["Jain", "University"]
print("\nList containing multiple values: ")
print(List[0])
print(List[1])

Output:

14
Set:
# Creating a Set
set1 = set()
print("Intial blank Set: ")
print(set1)
# Creating a Set with
# the use of a String
set1 = set("Jain University")
print("\nSet with the use of String: ")
print(set1)
# Creating a Set with
# the use of a List
set1 = set(["Jain", "University", "souvik"])
print("\nSet with the use of List: ")
print(set1)
# Creating a Set with
# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'Jain', 4, 'University', 6])
print("\nSet with the use of Mixed Values")
print(set1)

Output:

Dictionary:
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
15
# with Integer Keys
Dict = {1: 'Jain', 2: 'University', 3: 'Souvik'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Jain', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Jain', 2: 'University', 3: 'Souvik'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Jain'), (2, 'University')])
print("\nDictionary with each item as a pair: ")
print(Dict)

Output:

Tuple:
# Creating an empty tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
# Creating a Tuple with
# the use of Strings
Tuple1 = ('Jain', 'Univeraity')
print("\nTuple with the use of String: ")
print(Tuple1)
# Creating a Tuple with
# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
# Creating a Tuple with the
# use of built-in function
Tuple1 = tuple('Jain')
16
print("\nTuple with the use of function: ")
print(Tuple1)
# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Jain', 'University')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)

Output:

Write a python program to swap two numbers.


p=int(input('Enter first value'))
q=int(input('Enter 2nd value'))
print('Before Swapping the value of p=',p,'and q=',q)
temp=p
p=q
q=temp
print('After swapping the value of p=',p,'and q=',q)

Output:

Experiment -1
b. To perform mathematical operations such as addition, subtraction, multiplication, division, modulo, and
power; also explore the operator precedence.
Program:
a,b=[int(x) for x in input('Enter two Numbers (give coma in between
them):').split(',')]

17
print("Sum of",a,"and",b,"=",a+b)
print("subtraction from",a,"to",b,"=",a-b)
print("Multiplication of",a,"and",b,"=",a*b)
print("Division of",a,"by",b,"=",a/b)
print("Reminder after dividing",a,"by",b,"=",a%b)
print(a,"powerof",b,"=",a**b)
Output:

18
Experiment -2
Write programs to implement conditional operations on following:
a. Python program to find the sum and average of natural numbers up to n where n is provided by user.

Description :
 Allows a user to enter the number (n) he wishes to calculate the sum and average. The program
accepts user input using the input function.
 Next, run loop till the entered number using the for loop and range() function.
 Next, calculate the sum using a sum = sum + current number formula.
 At last, after the loop ends, calculate the average using average = sum / n. n is a number entered by
the user.
Program :
n=int (input("Enter upto which number you want sum and average"))
sum=0
avg=0

for i in range(0,n+1,1):
sum=sum+i
avg=sum/n
print("Total of first {} numbers is {}".format(n,sum))
print("Average of first {a} numbers is {b}".format(a=n,b=avg))

Output:

19
Experiment -2

B. Python program to find factorial, and Fibonacci of a number, received by user, with iterative as well
as recursive process.
Description: The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8,
13, 21, 34, 55, 89, 144, ……. A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8.... The first
two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This means to say the
nth term is the sum of (n-1)th and (n-2)th term. In mathematical terms, the sequence Fn of Fibonacci numbers
is defined by the recurrence relation
Program:
# Factorial of a number using
Iterative:
n=int(input("Enter number to get factorial"))
result=1
if n<0:
print("Factorial is not possible for negative number")
elif n==0:
print("Factorial of {} is {}".format(0,1))
else:
for i in range(n,0,-1):
result=result*i
print("Factorial of {} is {}".format(n,result))

Output:

# Python program to display the Fibonacci sequence


Iterative:
n = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto",n,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < n:
print(n1)
20
nth = n1 + n2
n1 = n2
n2 = nth
count += 1

Output:

Factorial of a number:
Recursive:
Def fact(n):
if n == 1:
return n
else:
return n*fact(n-1)

num = int(input("Enter a number: "))


if num<0:
print("Factorial can not be calculated for negative number")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",fact(num))

Output:

Output:

21
Recursive:
deffib(n):
if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))
nterms = int(input("How many terms? "))
ifnterms<= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(fib(i))
Output:

22
Experiment -3

Write python programs


a. To print all prime numbers between N and M.
Description: Prime numbers: A prime number is a natural number greater than 1 and having no positive
divisor other than 1 and itself. For example: 3, 7, 11 etc are prime numbers. Composite number: Other natural
numbers that are not prime numbers are called composite numbers. For example: 4, 6, 9 etc. are composite
numbers. Here is source code of the Python Program to check if a number is a prime number.
r=int(input("Enter upper limit: "))
for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(a)
Program:

n=int(input("Enter first number"))


m=int(input("Enter 2nd number"))
print('Prime numbers between',n,'and',m,'are:')
for numin range(n,m+1):
if num>1:
for i in range(2,num):
if(num%i)==0:
break
else:
print(num)
Output:

23
Experiment -3
b. To find largest among three numbers, input by user.
Program:
Ans:
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
n3 = int(input("Enter third number: "))

if (n1 > n2) and (n1 > n3):


largest = n1
elif(n2 > n1) and (n2 > n3):
largest = n2
else:
largest = n3

print("The largest number is", largest)

Output:

24
Experiment -3

c. To find GCD for two numbers, input by user


Description:
A simple solution is to find all prime factors of both numbers, then find intersection of all factors present in
both numbers. Finally return product of elements in the intersection.
An efficient solution is to use Euclidean algorithm which is the main algorithm used for this purpose. The
idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number.
Program:
defgcd(a,b):
if (b==0):
return a
else:
return gcd(b,a%b)
c,d=[int(x) for x in input('Enter two numbers for finding gcd (give a coma in between
them) : ').split(',')]
print('Gcdof',c,'and',d,'is :',gcd(c,d))

25
Experiment -4

Write python program to elaborate string operations such as


a) Implement a python script to check the element is in the list or not by using linear search & Binary
search.
Description: Start from the leftmost element of given arr[] and one by one compare element x with each
element of arr[]

If x matches with any of the element, return the index value.

If x doesn’t match with any of elements in arr[] , return -1 or element not found.

Now let’s see the visual representation of the given approach

Program:
search.
Linear Search:
deflinearsearch(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
print("element found at index "+str(linearsearch(arr,x)))

Output:

Description: In a nutshell, this search algorithm takes advantage of a collection of elements that is already
sorted by ignoring half of the elements after just one comparison.
1. Compare x with the middle element.
2. If x matches with the middle element, we return the mid index.
3. Else if x is greater than the mid element, then x can only lie in the right (greater) half subarray after the
mid element. Then we apply the algorithm again for the right half.
4. Else if x is smaller, the target x must lie in the left (lower) half. So we apply the algorithm for the left
half.

Program:
defbinary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elifarr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
26
else:
return -1
arr = [ 2, 3, 4, 10, 40 ]
x = 10
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print("Element",x,"is present at index", str(result))
else:
print("Element is not present in array")

Output:

27
Experiment -4

b) Implement a python script to arrange the elements in sorted order using Bubble, Selection, Insertion
and Merge sorting techniques.
Description: Bubble sort is one of the simplest sorting algorithms. The two adjacent elements of a list are
checked and swapped if they are in wrong order and this process is repeated until we get a sorted list. The
steps of performing a bubble sort are:
Compare the first and the second element of the list and swap them if they are in wrong order.
Compare the second and the third element of the list and swap them if they are in wrong order.
Proceed till the last element of the list in a similar fashion.
Repeat all of the above steps until the list is sorted.
Program :
Bubble Sort:
a = [16, 19, 11, 15, 10, 12, 14]
for j in range(len(a)):
swapped = False
i = 0
while i<len(a)-1:
if a[i]>a[i+1]:
a[i],a[i+1] = a[i+1],a[i]
swapped = True
i = i+1
if swapped == False:
break
print('The sorted order is:')
print (a)

Output:

Selection Sort:

Description: The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains
two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted
subarray is picked and moved to the sorted subarray.

28
a = [16, 19, 11, 15, 10, 12, 14]
i = 0
while i<len(a):
smallest = min(a[i:])
index_of_smallest = a.index(smallest)
a[i],a[index_of_smallest] = a[index_of_smallest],a[i]
i=i+1
print('The sorted list is:')
print (a)

Output:

Insertion Sort:
definsertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key <arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
arr = [16,19,11,15,10,12,14]
insertionSort(arr)
print("Sorted array is:")
for i in range(len(arr)):
print("%d" % arr[i])
Output:

Merge Sort:
defmergeSort(arr):
if len(arr) >1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i = j = k = 0
while i <len(L) and j <len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
29
arr[k] = R[j]
j += 1
k += 1
while i <len(L):
arr[k] = L[i]
i += 1
k += 1

while j <len(R):
arr[k] = R[j]
j += 1
k += 1
defprintList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
if __name__ == '__main__':
arr = [16,19,10,15,14,11,12]
print("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)

Output:

30
Experiment -5
Write Python program
a. Implement python script to show the usage of various operators available in python language.
Program:
Arithmetic Operation:
x = 15
y = 4
print('x=',x,'y=',y)
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)

Comparison Operator:
x = 10
y = 12
print('x=',x,'y=',y)
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)

Output:

Logical Operator:
x = True
y = False
print('x=',x,'y=',y)
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
Output:

31
Experiment -5

b. Write a program to calculate overtime pay of 10 employees. Overtime is paid at the rate of Rs.12.00 per
hour for every hour worked above 40 hours. Assume that employee do not work for fractional part of an
hour.
Program:
overtime_pay = 0
for i in range(10) :
print("Enter the time employee worked in hr ")
time_worked = int(input())
if (time_worked>40):
over_time = time_worked - 40
overtime_pay = overtime_pay + (12 * over_time)
print("\nTotal Overtime Pay Of 10 Employees Is ", overtime_pay)

Output:

32
Experiment -6

Write Python program using NumPy and pandas


a. Write a Pandas program to create and display a DataFrame from a specified dictionary data which has
the index labels.

Description:Pandas is one of the most widely used python libraries in data science. It provides high-
performance, easy to use structures and data analysis tools. Unlike NumPy library which provides objects for
multi-dimensional arrays, Pandas provides in-memory 2d table object called Dataframe. It is like a
spreadsheet with column names and row labels.

Hence, with 2d tables, pandas is capable of providing many additional functionalities like creating pivot
tables, computing columns based on other columns and plotting graphs. Pandas can be imported into Python
using:

>>> import pandas as pd

Some commonly used data structures in pandas are:

 Series objects: 1D array, similar to a column in a spreadsheet


 DataFrame objects: 2D table, similar to a spreadsheet
 Panel objects: Dictionary of DataFrames, similar to sheet in MS Excel
Pandas Series object is created using pd.Series function. Each row is provided with an index and by defaults
is assigned numerical values starting from 0. Like NumPy, Pandas also provide the basic mathematical
functionalities like addition, subtraction and conditional operations and broadcasting.

Pandasdataframe object represents a spreadsheet with cell values, column names, and row index labels.
Dataframe can be visualized as dictionaries of Series. Dataframe rows and columns are simple and intuitive
to access. Pandas also provide SQL-like functionality to filter, sort rows based on conditions.

Program:
import pandas as pd
importnumpy as np

exam_data = {'name': ['Kishor', 'Souvik', 'Shaktivel', 'Bhavan', 'Kapish', 'Suryaprakash', 'Abhishek',


'Vinayak', 'Krishna', 'Kaveri'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

df = pd.DataFrame(exam_data , index=labels)
print(df)

Output:

33
Experiment -6

b. To create a 4X2 integer array and prints its attributes.

Program:
import numpy
firstArray = numpy.empty([4,2], dtype= numpy.uint16)
print("Printing Array")
print(firstArray)
print("Printing numpy array Attributes")
print("1> Array Shape is: ", firstArray.shape)
print("2>. Array dimensions are ", firstArray.ndim)
print("3>. Length of each element of array in bytes is ", firstArray.itemsize)

Output:

Experiment -6

c. For the given numpy array return array of odd rows and even columns.
Program :
import numpy
sampleArray = numpy.array([[3 ,6, 9, 12], [15 ,18, 21, 24],
[27 ,30, 33, 36], [39 ,42, 45, 48], [51 ,54, 57, 60]])
print("Printing Input Array")
print(sampleArray)
print("\n Printing array of odd rows and even columns")
newArray = sampleArray[::2, 1::2]
print(newArray)

34
Output:

Experiment -6

d. To add the two NumPy arrays and modify a result array by calculating the square root ofeach element.

Program :
import numpy
arrayOne = numpy.array([[5, 6, 9], [21 ,18, 27]])
arrayTwo = numpy.array([[15 ,33, 24], [4 ,7, 1]])
resultArray = arrayOne + arrayTwo
print("addition of two arrays is \n")
print(resultArray)
for numin numpy.nditer(resultArray, op_flags= ['readwrite']):
num[...] = num*num
print("\nResult array after calculating the square root of all elements\n")
print(resultArray)

Output:

35
Experiment -7
Write python program to show following plots using Matplotlib library.[ General case study]
a. To read total profit of all months and show it using a line plot where x axis should be month number
and y axis should be named as total profit.
Description:Matplotlib is a 2d plotting library which produces publication quality figures in a variety of
hardcopy formats and interactive environments. Matplotlib can be used in Python scripts, Python and IPython
shell, Jupyter Notebook, web application servers and GUI toolkits.
matplotlib.pyplot is a collection of functions that make matplotlib work like MATLAB. Majority of plotting
commands in pyplot have MATLAB analogs with similar arguments. 
Program :
import pandas as pd
importmatplotlib.pyplot as plt
df = pd.read_csv("D:\\Python\\Articles\\matplotlib\\sales_data.csv")
profitList = df ['total_profit'].tolist()
monthList =df ['month_number'].tolist()
plt.plot(monthList, profitList, label = 'Month-wise Profit data of last year')
plt.xlabel('Month number')
plt.ylabel('Profit in dollar')
plt.xticks(monthList)
plt.title('Company profit per month')
plt.yticks([100000, 200000, 300000, 400000, 500000])
plt.show()
Output:

36
Experiment -7

b. To get total profit of all months and show line plot with the following style properties
Line Style dotted and Line-color should be red
Show legend at the lower right location.
X label name = Month Number
Y label name = Sold units number
Add a circle marker.
Line marker color as read
Line width should be 3.
Program :
import pandas as pd
import matplotlib.pyplotas plt
df = pd.read_csv("D:\\Python\\Articles\\matplotlib\\sales_data.csv")
monthList = df ['month_number'].tolist()
faceCremSalesData = df ['facecream'].tolist()
faceWashSalesData = df ['facewash'].tolist()
toothPasteSalesData = df ['toothpaste'].tolist()
bathingsoapSalesData = df ['bathingsoap'].tolist()
shampooSalesData = df ['shampoo'].tolist()
moisturizerSalesData = df ['moisturizer'].tolist()
plt.plot(monthList, faceCremSalesData, label = 'Face cream Sales Data', marker='o',
linewidth=3)
plt.plot(monthList, faceWashSalesData, label = 'Face Wash Sales Data', marker='o',
linewidth=3)
plt.plot(monthList, toothPasteSalesData, label = 'ToothPaste Sales Data', marker='o',
linewidth=3)
plt.plot(monthList, bathingsoapSalesData, label = 'ToothPaste Sales Data', marker='o',
linewidth=3)
plt.plot(monthList, shampooSalesData, label = 'ToothPaste Sales Data', marker='o',
linewidth=3)
plt.plot(monthList, moisturizerSalesData, label = 'ToothPaste Sales Data', marker='o',
linewidth=3)
plt.xlabel('Month Number')
plt.ylabel('Sales units in number')
plt.legend(loc='upper left')
plt.xticks(monthList)
plt.yticks([1000, 2000, 4000, 6000, 8000, 10000, 12000, 15000, 18000])
plt.title('Sales data')
plt.show()

Output:

37
Experiment -8

Write python programs for following graphical objects

a) Draw the target symbol (a set of concentric squares, alternating red and white) in a graphics window, that is, 200
pixels wide by 200 pixels high. (Hint: Draw the target square first in red, followed by next smaller square in
white, then draw the next smaller square in red).

Program:
import matplotlib.pyplot as plt
plt.axes

rectangle=plt.Rectangle((0,0),200,200,fc='red')
plt.gca().add_patch(rectangle)

rectangle=plt.Rectangle((50,50),100,100,fc='white')
plt.gca().add_patch(rectangle)

rectangle=plt.Rectangle((75,75),50,50,fc='red')
plt.gca().add_patch(rectangle)

plt.axis("scaled")
plt.show()

output:

38
Experiment -8

Create a 5x5 rectangle whose top left corner is at (row*5, col*5). If the sum of the rows and columns’ number is even, set the
fill color of the rectangle to white, otherwise set it to the black. Then draw the rectangle.

Program:
from matplotlib import pyplot as plot
plt.figure()
plt.axis([0,25,25,0])
currentAxis=plt.gca()
for i in range(0,5):
for j in range(0,5):
if((i+j)%2==0):
currentAxis.add_patch(plt.Rectangle((i*5,j*5),5,5,color='white'))
else:
currentAxis.add_patch(plt.Rectangle((i*5,j*5),5,5,color='black'))

plt.show()

output:

39
Experiment -9
Cryptography algorithms with python programming – I

A. Write a python program to implement Caesar cipher symmetric encryption method


Description
The algorithm of Caesar cipher holds the following features −

 Caesar Cipher Technique is the simple and easy method of encryption technique.
 It is simple type of substitution cipher.
 Each letter of plain text is replaced by a letter with some fixed number of positions down with
alphabet.

The following diagram depicts the working of Caesar cipher algorithm implementation −

Program:
def encrypt(text,s):
result = " "
# transverse the plain text
for i in range(len(text)):
char = text[i]
# Encrypt uppercase characters in plain text
if (char.isupper()):
result += chr((ord(char) + s-65) % 26 + 65)
# Encrypt lowercase characters in plain text
else:
result += chr((ord(char) + s - 97) % 26 + 97)
return result

#check the above function


text = "CEASER CIPHER DEMO"
s=4

print ("Plain Text : " + text)


print ("Shift pattern : " + str(s))
print ("Cipher: " + encrypt(text,s))
40
output:

41
B. Write a python program to decrypt a message encrypted using Caesar cipher method.

Description - Hacking of Caesar Cipher Algorithm

 The cipher text can be hacked with various possibilities. One of such possibility is Brute Force
Technique, which involves trying every possible decryption key. This technique does not demand
much effort and is relatively simple for a hacker.
 The program implementation for hacking Caesar cipher algorithm is as follows −

Program

Output

42
C. Write a python program to hack Caesar cipher symmetric encryption method using brute force
technique.

Encryption code:

OUTPUT

43
Decryption

OUTPUT

D. Write a python program to implement XOR algorithm for encryption and decryption of an input
message.
Description

XOR algorithm of encryption and decryption converts the plain text in the format ASCII bytes and uses XOR
procedure to convert it to a specified byte. It offers the following advantages to its users −

 Fast computation
 No difference marked in left and right side
 Easy to understand and analyze

44
Output

45
Experiment - 10
Cryptography algorithms with python programming– II

A. Write a python program to implement transposition cipher encryption method


Description

Transposition Cipher is a cryptographic algorithm where the order of alphabets in the plaintext is rearranged
to form a cipher text. In this process, the actual plain text alphabets are not included.

Example - A simple example for a transposition cipher is columnar transposition cipher where each
character in the plain text is written horizontally with specified alphabet width. The cipher is written
vertically, which creates an entirely different cipher text.

Consider the plain text hello world, and let us apply the simple columnar transposition technique as shown
below

The plain text characters are placed horizontally and the cipher text is created with vertical format as :
holewdlo lr. Now, the receiver has to use the same table to decrypt the cipher text to plain text.

Program
import math
def encrypt(key, message):
# Simulates columns in the matrix by using string array.
ciphertext = [''] * key
# Iterates through each column in the ciphertext.
for column in range(key):
index = column
# Iterates until the plaintext end.
while index < len(message):
# Places the character at the end of the column:
ciphertext[column] += message[index]
# Moves the index to the next symbol.
index += key

# Returns the ciphertext array as a single string.


return ''.join(ciphertext)

46
def decrypt(key, message):
# Calculates the matrix dimensions: how many rows and columns
# - we need this for position tracking.
nrows = key
ncols = math.ceil(len(message) / key)

# Calculates the number of empty positions in the matrix due to


# the ceil() function.
empty_positions = nrows * ncols - len(message)

# Simulates columns in the matrix by using string array.


plaintext = [''] * ncols

# Initializes the position tracking variables.


column = 0
row = 0

# Iterates through each symbol in the ciphered message.


for symbol in message:
# Fills the matrix in a row by row movement pattern.
plaintext[column] += symbol
column += 1

# In case we're positioned after the last column...


# ... or at the position that should be empty - such positions are
# possible only in the last column - wrap to the start of the next row.
if column == ncols or (column == ncols - 1 and row >= nrows - empty_positions):
column = 0
row += 1

# Returns the plaintext array as a single string.


return ''.join(plaintext)

47
message = 'Here is our first message!'
key = 6
ciphertext = encrypt(key, message)
# Delimits the ciphertext for displaying purposes, i.e. to show
# a <space> symbol if there is one at the end.
print(f'Ciphertext: {ciphertext}<end>')
# Prints the plaintext for algorithm validity checking.
plaintext = decrypt(key, ciphertext)
print(f'Plaintext: {plaintext}')

OUTPUT

B. Write a python program to decrypt a message encrypted using transposition cipher method.

Program:

Output:

Program:
# Transposition Cipher Decryption
import math, pyperclip

48
def main():
myMessage = 'Cenoonommstmme oo snnio. s s c'
myKey = 8
plaintext = decryptMessage(myKey, myMessage)
print(plaintext + '|')
pyperclip.copy(plaintext)
def decryptMessage(key, message):
# The transposition decrypt function will simulate the "columns" and
# "rows" of the grid that the plaintext is written on by using a list
# of strings. First, we need to calculate a few values.
# The number of "columns" in our transposition grid:
numOfColumns = math.ceil(len(message) / key)
# The number of "rows" in our grid will need:
numOfRows = key
# The number of "shaded boxes" in the last "column" of the grid:
numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)
# Each string in plaintext represents a column in the grid.
plaintext = [''] * numOfColumns
# The col and row variables point to where in the grid the next
# character in the encrypted message will go.
col = 0
row = 0
for symbol in message:
plaintext[col] += symbol
col += 1 # point to next column
# If there are no more columns OR we're at a shaded box, go back to
# the first column and the next row.
if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows -
numOfShadedBoxes):
col = 0
row += 1
return ''.join(plaintext)
# If transpositionDecrypt.py is run (instead of imported as a module) call
# the main() function.
if __name__ == '__main__':
main()
49
Output:

C. Write a python program to implement polyalphabetic Cipher.

Rubrics for Evaluation (CIA and Semester End Assessment)

Sl. Assessment Formative/ Frequency Weightage CO


N Instrument Summative (%)
o.
1. Continuous Assessment Formative Continuous 70 CO1 to CO6
2. Semester End Test Summative 1 30 CO1 to CO6
Total 100

50
51

You might also like