0% found this document useful (0 votes)
15 views

6cs4-23 Python Lab Manual 2022-23

The Python Lab Manual for Poornima College of Engineering outlines the lab's vision, mission, syllabus, and experiments for the 2022-23 academic session. It includes detailed instructions for conducting experiments, evaluation schemes, and general lab rules. The manual aims to equip students with fundamental Python programming skills and emphasizes the importance of safety and proper lab conduct.

Uploaded by

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

6cs4-23 Python Lab Manual 2022-23

The Python Lab Manual for Poornima College of Engineering outlines the lab's vision, mission, syllabus, and experiments for the 2022-23 academic session. It includes detailed instructions for conducting experiments, evaluation schemes, and general lab rules. The manual aims to equip students with fundamental Python programming skills and emphasizes the importance of safety and proper lab conduct.

Uploaded by

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

Poornima College of Engineering, Jaipur Python Lab Manual

ISI-6, RIICO Institutional Area, Sitapura, Jaipur-302022, Rajasthan


Phone/Fax: 0141-2770790-92, www.pce.poornima.org

Python LAB
(Lab Code: 6CS4-23)
6thSemester, 3thYear

Department of Computer Engineering


Session: 2022-23
Poornima College of Engineering, Jaipur Python Lab Manual

TABLE OF CONTENT
S.No. Topic/Name of Experiment Page
Number
GENERAL DETAILS

1 Vision & Mission of Institute and Department iv

2 RTU Syllabus and Marking Scheme v

3 Lab Outcomes and its Mapping with POs and PSOs vi

4 Lab Conduction Plan viii

5 General Lab Instructions ix

6 Lab Specific Safety Rules x

LIST OF EXEPERIMENTS WITH VIVA QUESTIONS (AS PER RTU SYLLABUS)

A Zero Lecture 1
Write a program to demonstrate basic data type in python. 2
1
Write a program to compute distance between two points taking input 3
2 from the user Write a program add.py that takes 2 numbers as command
line arguments and prints its sum.
3 Write a Program for checking whether the given number is an even 4
number or not. Using a for loop, write a program that prints out the
decimal equivalents of 1/2, 1/3, 1/4, . . . , 1/10.
Write a Program to demonstrate list and tuple in python. Write a program 5
4 using a for loop that loops over a sequence. Write a program using a
while loop that asks the user for a number, and prints a countdown from
that number to zero.
Find the sum of all the primes below two million. By considering the 8
5 terms in the Fibonacci sequence whose values do not exceed four million,
WAP to find the sum of the even-valued terms.
Write a program to count the numbers of characters in the string and 9
store them in a dictionary data structure Write a program to use split
6
and join methods in the string and trace a birthday of a person with
a dictionary data structure.
Write a program to count frequency of characters in a given file. Can 11
you use character frequency to tell whether the given file is a Python
program file, C program file or a text file? Write a program to count
7
frequency of characters in a given file. Can you use character frequency
to tell whether the given file is a Python program file, C program file or
a text file?
Write a program to print each line of a file in reverse order. Write a 12
8
program to compute the number of characters, words and lines in a file.
Write a function nearly equal to test whether two strings are nearly 13
equal. Two strings a and b are nearly equal when a can be generated by
9
a single mutation on. Write function to compute gcd, lcm of two
numbers. Each function shouldn’t exceed one line.
Write a program to implement Merge sort. Write a program to 14
10
implement Selection sort, Insertion sort.
ii
Poornima College of Engineering, Jaipur Python Lab Manual

11 Beyond the Syllabus Experiment-1 17

12 Beyond the Syllabus Experiment-2 19

iii
Poornima College of Engineering, Jaipur Python Lab Manual

INSTITUE VISIONAND MISSION


VISION
To create knowledge based society with scientific temper, team spirit and dignity of labor
to face the global competitive challenges

MISSION
To evolve and develop skill based systems for effective delivery of knowledge so as to
equip young professionals with dedication & commitment to excellence in all spheres of
life.

DEPARTMENT VISION & MISSION

VISION
Evolve as a center of excellence with wider recognition and to adapt the rapid innovation in
Computer Engineering.

MISSION

 To provide a learning-centered environment that will enable students and faculty members to
achieve their goals empowering them to compete globally for the most desirable careers in
academia and industry.

 To contribute significantly to the research and the discovery of new arenas of knowledge and
methods in the rapid developing field of Computer Engineering.

 To support society through participation and transfer of advanced technology from one sector to
another.

iv
Python Lab (6CS4-23) Manual 2022-23
Department of Computer Engineering
Poornima College of Engineering, Jaipur Python Lab Manual

RTU SYLLABUS AND MARKING SCHEME


6CS4-23: Python LAB

Credit:1.5 Max. Marks: 100(IA:45,ETE:20)

0L+0T+3P End Term Exam: 2Hours


S. No. NAME OF EXPERIMENTS
Write a program to demonstrate basic data type in python.
1
Write a program to compute distance between two points taking input From the user
2
Write a program add.py that takes 2 numbers as command line arguments and prints
its sum.

3 Write a Program for checking whether the given number is an even number or
not. Using a for loop, write a program that prints out the Decimal equivalents
of 1/2, 1/3, 1/4,. . . , 1/10.
WriteaProgramtodemonstratelistandtupleinpython.Writeaprogramusingafor loop
4
that loops over a sequence. Write a program using a while loop that asks the user for
a number, and prints a count down from that number to zero.
Find the sum of all the primes below two million. By considering the terms in the
5
Fibonacci sequence whose values do not exceed four million, WAP to find the sum
of the even-valued terms.
Write a program to count the numbers of characters in the string and store
6
them in a dictionary data structure Write a program to Use split and join
methods in the string and trace a birthday of a person with a dictionary data
structure.
Write a program to count frequency of characters in a given file. Can you use
7
character frequency to tell whether the given file is a Python program file, C
program file or a text file? Write a program to count frequency of characters in a
given file. Can you use character frequency to tell whether the given file is a Python
program file, C program file or A text file?

8 Write a program to print each line of a file in reverse order. Write a program to
compute the number of characters, words and lines in a file.
Write a function nearly equal to test whether two strings are nearly equal. Two
9
strings a and b are nearly equal when a can be generated by a single mutation on.
Write function to compute gcd, lcm of two numbers. Each function shouldn’t
exceed one line.

v
Python Lab (6CS4-23) Manual 2022-23
Department of Computer Engineering
Poornima College of Engineering, Jaipur Python Lab Manual

10 Write a program to implement Merge sort. Write a program to implement Selection


sort, Insertion sort.

EVALUATION SCHEME

I+II Mid Term Examination Attendance and performance End Term Examination
Total Marks
Experiment Viva Total Attendance Performance Total Experiment Viva Total

20 10 30 5 5 10 20 10 30 100

DISTRIBUTION OF MARKS FOR EACH EXPERIMENT

Attendance Record Performance Total


2 3 5 10

vi
Python Lab (6CS4-23) Manual 2022-23
Department of Computer Engineering
Poornima College of Engineering, Jaipur Python Lab Manual

LAB OUTCOME AND ITS MAPPING WITH PO & PSO

LAB OUTCOMES

Objectives of this lab are as follows:


 To study the various
 To learn the basics of python as a programming language.
To learn the fundamental activities to develop programs using python data types.
Outcomes:-
 Students will develop basic programs of python like maximum, sum, prime,
even and odd.
 Students will apply the knowledge different data types of python.
Students can use the extensive library of python and since its open source and can be
easily integrated
Lab Outcomes:

LO1 Identify the basic datatypes and variables .

LO2 Ability to analyze the importance of conditional statement & Looping Structure.

LO3 Determine the list and tuples in container data types.

Able to Implement String ,Character Arrays and Fuction Programming concept in


LO4
python.

LO5 Develop the ability to analyse data structure applications in Python programming.

LO-PO-PSO MAPPING MATRIX OF COURSE


LO/PO/P PO PO PO PO PO PO PO PO PO PO1 PO PO1 PS PS PS
SO 1 2 3 4 5 6 7 8 9 0 11 2 O1 O2 O3
LO1 2 - - - - - - - - - - - 3 - -
LO2 - 3 - - - - - - - - - - 3 3 -
LO3 - - 3 - - - - - - - - - - - 2
LO4 - - - 3 - - - - - - - - - - 3
LO5 - - - - 2 - - - - - - - - 3 3

PROGRAM OUTCOMES (POs)

Engineering knowledge: Apply the knowledge of mathematics, science, engineering


PO1 fundamentals, and an engineering specialization to the solution of complex engineering
problems

vii
Python Lab (6CS4-23) Manual 2022-23
Department of Computer Engineering
Poornima College of Engineering, Jaipur Python Lab Manual

Problem analysis: Identify, formulate, review research literature, and analyze complex
PO2 engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

Design/development of solutions: Design solutions for complex engineering


PO3 problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge and
PO4 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
PO5 modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.

The engineer and society: Apply reasoning informed by the contextual knowledge to
PO6 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


PO7 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
PO8 and norms of the engineering practice.
Individual and teamwork: Function effectively as an individual, and as a member or
PO9 leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the
PO10 engineering community and with society at large, such as, being able to 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
PO11 engineering and management principles and apply the setoone’s own work, as a
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
PO12 engage in independent and life-long learning in the broadest context of technological
change.

PROGRAM SPECIFIC OUTCOMES (PSOs)

Design, an alyze and innovate solutions to technical issues in Thermal, Production


PSO1 and Design engineering.

PSO2 Exhibit the knowledge and skills in the field of Mechanical & Allied engineering
concepts.
PSO3 Apply the knowledge of skills in HVAC & Rand Automobile engineering.

vii
Python Lab (6CS4-23) Manual 2022-23 i
Department of Computer Engineering
Poornima College of Engineering, Jaipur Python Lab Manual

LAB CONDUCTION PLAN

Total number of experiment: 10


Total number of turns required: 10
Number of turns required for:

Experiment Number Turns Scheduled Week


Exp. 1 1 Week 1
Exp. 2 1 Week 2
Exp. 3 1 Week 3
Exp. 4 1 Week 4
Exp. 5 1 Week 5
Exp. 6 1 Week 6
Exp. 7 1 Week 7
Exp. 8 1 Week 8
Exp. 9 1 Week 9
Exp. 10 1 Week 10

DISTRIBUTIONOF LAB HOURS

Distribution of Lab Hours


S. No. Activity
Time(120minute)
1 Attendance 5
2 Explanation of features of language 30
3 Explaining the Experiment 15
4 Performance of experiment 45
5 Viva/Quiz/Queries 25

ix
Python Lab (6CS4-23) Manual 2022-23
Department of Computer Engineering
Poornima College of Engineering, Jaipur Python Lab Manual

GENERAL LAB INSTRUCTIONS

DO’S
 Enter the lab on time and leave at proper time.
 Wait for the previous class to leave before the next class enters.
 Keep the bag outside in the respective racks.
 Utilize lab hours in the corresponding.
 Turn off the machine before leaving the lab unless a member of lab staff has specifically
told you not to do so.
 Leave the labs at least as nice as you found them.
 If you notice a problem with a piece of equipment (e.g. a computer doesn't respond) or the
room in general (e.g. cooling, heating, lighting) please report it to lab staff immediately.
Do not attempt to fix the problem yourself.

DON’TS
 Don't abuse the equipment.
 Do not adjust the heat or air conditioners. If you feel the temperature is not properly set,
inform lab staff; we will attempt to maintain a balance that is healthy for people and
machines.
 Do not attempt to reboot a computer. Report problems to lab staff.
 Do not remove or modify any software or file without permission.
 Do not remove printers and machines from the network without being explicitly told to do
so by lab staff.
 Don't monopolize equipment. If you're going to be away from your machine for more than
10 or 15 minutes, log out before leaving. This is both for the security of your account, and
to ensure that others are able to use the lab resources while you are not.
 Don’t use internet, internet chat of any kind in your regular lab schedule.
 Do not download or upload of MP3, JPG or MPEG files.
 No games are allowed in the lab sessions.
 No hardware including USB drives can be connected or disconnected in the labs without
prior permission of the lab in-charge.
 No food or drink is allowed in the lab or near any of the equipment. Aside from the fact that
it leaves a mess and attracts pests, spilling anything on a keyboard or other piece of computer
equipment could cause permanent, irreparable, and costly damage. (and in fact has) If you
need to eat or drink, take a break and do so in the canteen.
 Don’t bring any external material in the lab, except your lab record, copy and books.
 Don’t bring the mobile phones in the lab. If necessary then keep them in silence mode.
 Please be considerate of those around you, especially in terms of noise level. While labs are
a natural place for conversations of all types, kindly keep the volume turned down.

If you are having problems or questions, please go to either the faculty, lab in-charge or the lab
supporting staff. They will help you. We need your full support and cooperation for smooth
functioning of the lab.

x
Python Lab (6CS4-23) Manual 2022-23
Department of Computer Engineering
Poornima College of Engineering, Jaipur Python Lab Manual

LAB SPECIFIC SAFETY RULES

Before entering in the lab

 All the students are supposed to prepare the theory regarding the next experiment/
Program.
 Students are supposed to bring their lab records as per their lab schedule.
 Previous experiment/program should be written in the lab record.
 If applicable trace paper/graph paper must be pasted in lab record with proper labeling.
 All the students must follow the instructions, failing which he/she may not be allowed in
the lab.

While working in the lab

 Adhere to experimental schedule as instructed by the lab in-charge/faculty.


 Get the previously performed experiment/ program signed by the faculty/ lab in charge.
 Get the output of current experiment/program checked by the faculty/ lab in charge in the
lab copy.
 Each student should work on his/her assigned computer at each turn of the lab.
 Take responsibility of valuable accessories.

xi
Python Lab (6CS4-23) Manual 2022-23
Department of Computer Engineering
Poornima College of Engineering, Jaipur Python Lab Manual

Zero Lecture

Topic to be covered: Installations, Indentations, Comments, Variables, Data Types, Casting, User
inputs

1) Introduction of Python and installation of anaconda Jupyter by students.

Prerequisite: Python

While Jupyter runs code in many programming languages, Python is a requirement (Python 3.3 or
greater, or Python 2.7) for installing the Jupyter Notebook. We recommend using the Anaconda
distribution to install Python and Jupyter.

Installing Jupyter using Anaconda

For new users, we highly recommend installing Anaconda. Anaconda conveniently installs Python, the
Jupyter Notebook. Use the following installation steps:

Download Anaconda. We recommend downloading Anaconda’s latest Python 3 version (currently


Python 3.5).
Install the version of Anaconda which you downloaded, following the instructions on the download
page.
Congratulations, you have installed Jupyter Notebook.

Python Lab (6CS4-23) Manual 2022-23 1 Department of Computer Engineering


Poornima College of Engineering, Jaipur Python Lab Manual

Experiment–1

AIM: Write a program to demonstrate basic data type in python.

Program:

print(type(1))
print(type(2.2))
print(type('ABCD'))
print(type([1,2,3]))
print(type({1:'a'}))
print(type((1,2,3)))
print(type({1,2,3}))

Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'tuple'>
<class 'set'>

Python Lab (6CS4-23) Manual 2022-23 2 Department of Computer Engineering


Poornima College of Engineering, Jaipur Python Lab Manual

Experiment–2

AIM:
 Write a program to compute distance between two points taking input
from the user.

Program:
#formula : sqrt((x2 - x1)^2 + (y2 - y1)^2).
x1= int(input("enter X1 value"))
x2= int(input("enter X2 value"))
y1= int(input("enter y1 value"))
y2= int(input("enter y2 value"))
result=(((x2-x1)**2 + (y2-y1)**2)**0.5)
print("the distance between two points",(x1,x2),"and",(y1,y2),"=",result)

Output:
enter X1 value5
enter X2 value6
enter y1 value4
enter y2 value3
the distance between two points (5, 6) and (4, 3) = 1.4142135623730951

 Write a program add.py that takes 2 numbers as input from user and prints its sum.

Program:

num1=int(input("Enter the first Number"))


num2=int(input("Enter the Second Number"))
sum=num1+num2
print("The Sum of Two numbers is", sum)

Output:
Enter the first Number 5
Enter the Second Number 4
The Sum of Two numbers is 9

Python Lab (6CS4-23) Manual 2022-23 3 Department of Computer Engineering


Poornima College of Engineering, Jaipur Python Lab Manual

Experiment–3

AIM:
 Write a Python program to check given number is even or not.

Program:
number=int(input("enter the number to be check"))
if (number%2==0):
print("number is even")
else:
print("number is not even")

Output:
enter the number to be check5
number is not even

 Using a for loop, write a program that prints out the decimal equivalents of ½, 1/3, 1/4… 1/10

Program:

for i in range(2,11):
print(1/i)

Output:
0.5
0.3333333333333333
0.25
0.2
0.16666666666666666
0.14285714285714285
0.125
0.1111111111111111
0.1

Python Lab (6CS4-23) Manual 2022-23 4 Department of Computer Engineering


Poornima College of Engineering, Jaipur Python Lab Manual

Experiment–4

AIM:
 Write a program using a for loop that loops over a sequence.

Program:
#For loop in list
color_list=['red','green','white','purple','pink','marron']
for i in color_list:
print(i)
#For loop in string
fr_string="Goeduhub technologies"
for i in fr_string:
print(i)
#For loop in dictionary
fr_dict={1:'q',2:'w',3:'e',4:"r"}
for i in fr_dict:
print(i)
print(fr_dict[i])
#Sum of all the list elements
Num=[1,2,3,4,5,6,7,8,9,10]
Sum=0
for i in Num:
Sum=Sum+i
print(Sum)

Output:
red
green
white
purple
pink
marron
G
o
e
d
u
h
u
b

5
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering
Poornima College of Engineering, Jaipur Python Lab Manual

t
e
c
h
n
o
l
o
g
i
e
s
1
q
2
w
3
e
4
R
55

 Write a program using while loop that asks the user for a number, and prints a countdown
from that number to zero.

Program:
num=int(input("Enter your number"))
while(num>=0):
print(num)
num=num-1
Output:
Enter your number5
5
4
3
2
1
0

 Write a program to demonstrate list in python


Program:
#Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
Print the number of items in the list:

6
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering
Poornima College of Engineering, Jaipur Python Lab Manual

thislist = ["apple", "banana", "cherry"]


print(len(thislist))
#Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
#Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon"]
print(thislist[2:5])

 Write a program to demonstrate tuples in python

Program:
#Example
#Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
#Example
#Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
#Example
#One item tuple, remember the commma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
#Example
#A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
print(tuple1)
#Example
#Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[0])
#Example
#Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-2])
#Example
#Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

7
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering
Poornima College of Engineering, Jaipur Python Lab Manual

Experiment–5

AIM:
 Find the sum of all the primes below two million.

Program:
def IsPrime(x):
returnVal = True
for i in range(2,int(x)):
if (int(x) % i)==0:
returnVal=False
break
return returnVal
###################################3

sum=2

for i in range(3,2000000):
if IsPrime(i):
print("adding " + str(i))
sum = sum + i
print(sum)

 By considering the terms in the Fibonacci sequence whose values do not exceed
four million, WAP to find the sum of the even-valued terms.

Program:
sum = 2
a=1
b=2
c=0

while c <= 4000000:


c=a+b
if c%2 == 0:
sum += c

a,b = b,c

print(sum)

8
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering
Poornima College of Engineering, Jaipur Python Lab Manual

Experiment-6

AIM:
 Write a program to count the numbers of characters in the string and store them in a
dictionary data structure
Program:
str=input("enter string : ")
f = {}
for i in str:
#print (i)
if i in f:
f[i] += 1
else:
f[i] = 1
print(f)
Output:
enter string : shikha
{'s': 1, 'h': 2, 'i': 1, 'k': 1, 'a': 1}

 Write a program to use split and join methods in the string and trace a birthday of a
person with a dictionary data structure

Program:
bdaystr=input("Enter date of birth:\n")
bdaylist=bdaystr.split("/")
print(bdaylist)
bday='-'.join(bdaylist)
bdaydict={"birthday":bday}
print(bdaydict['birthday'])
req= input("enter bday to match")
if bdaydict['birthday']==req:
print("yes,Birthday date matched")

9
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering
Poornima College of Engineering, Jaipur Python Lab Manual

else:
print("no,Birthday date not matched")

Output:
Enter date of birth:
22/4/2020
['22', '4', '2020']
22-4-2020
enter bday to match23-4-2020
no,Birthday date not matched

10
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering
Poornima College of Engineering, Jaipur Python Lab Manual

Experiment-7

AIM: Write a program to count frequency of characters in a given file. Can you use character
frequency to tell whether the given file is a Python program file, C program file or a text file?

Program:
f="D:\\myfile\demofile.txt"
file = open ( f, "r" )
a=[]
b={}
for i in file:
for j in range(0,len(i)):
a.append(i[j])
print(a)
for i in a:
if i in b:
b[i]+=1
else:
b[i]=1
print(b)
c=f.split(".")
if c[1]=="txt":
print("\n\nit is a text file")
elif c[1]=="cpp":
print("\n\nit is a c++ file")
else:
print("\n\nit is a c file")

Output:
['W', 'o', 'o', 'p', 's', '!', ' ', 'I', ' ', 'h', 'a', 'v', 'e', ' ', 'd', 'e', 'l', 'e', 't', 'e', 'd', ' ', 't', 'h', 'e', ' ', 'c', 'o', 'n', 't', 'e', 'n', 't', '!']
{'W': 1, 'o': 3, 'p': 1, 's': 1, '!': 2, ' ': 5, 'I': 1, 'h': 2, 'a': 1, 'v': 1, 'e': 6, 'd': 2, 'l': 1, 't': 4, 'c': 1, 'n': 2}

it is a text file

11
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering
Poornima College of Engineering, Jaipur Department of Computer Engineering

Experiment-
12

AIM:
 Write a program to print each line of a file in reverse order.

Program:
ofile=open("D:\\myfile\demofile.txt","r")
k=ofile.readlines()
t=reversed(k)
for i in t:
print(i.rstrip())
ofile.close()

Output:

we are performing experiments


we are performing experiments
we are performing experiments
file handling concepts we are performing experiments we are performing experiments
this is my first file
world
hello

 Write a program to compute the number of characters, words and lines in file.

Program:

file = open("D:\\myfile\demofile.txt","r")
number_of_lines = 0
number_of_words = 0
number_of_characters = 0
for line in file:
line = line.strip()
words = line.split()
number_of_lines += 1
number_of_words += len(words)
number_of_characters += len(line)
file.close()
print("lines:", number_of_lines, "words:", number_of_words, "characters:",
number_of_characters)

Output:

lines: 7 words: 30 characters: 200

12
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering
Poornima College of Engineering, Jaipur Department of Computer Engineering

Experiment-9

AIM:
 Write a function nearly equal to test whether two strings are nearly equal. Two strings a
and b are nearly equal when a can be generated by a single mutation on.

Program:
string1 = input("Enter first string: ")
string2 = input("Enter second string: ")
if string1 == string2:
print("\nBoth strings are equal to each other.")
print(string1,"==",string2);
else:
print("\nStrings are not equal.")
print(string1,"!=",string2);

Output:

Enter first string: barkha


Enter second string: barkha
Both strings are equal to each other.
barkha == barkha

 Write function to compute gcd, lcm of two numbers. Each function shouldn’t exceed one
line.

Program:

def gcd(x, y):


while(y):
x, y = y, x % y
return x
# This function computes LCM
def lcm(x, y):
lcm = (x*y)//gcd(x,y)
return lcm
num1 = 60
num2 = 48
print("The L.C.M. is", lcm(num1, num2))
print("GCD of two numbers is ",gcd(num1,num2))

Output:
The L.C.M. is 240

13
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering
Poornima College of Engineering, Jaipur Department of Computer Engineering

GCD of two numbers is 12

Experiment-10

AIM:
 Write a program to implement Merge sort.

Program:
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m

# create temp arrays


L = [0] * (n1)
R = [0] * (n2)

# Copy data to temp arrays L[] and R[]


for i in range(0, n1):
L[i] = arr[l + i]

for j in range(0, n2):


R[j] = arr[m + 1 + j]

# Merge the temp arrays back into arr[l..r]


i = 0 # Initial index of first subarray
j = 0 # Initial index of second subarray
k = l # Initial index of merged subarray

while i < n1 and j < n2:


if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1

# Copy the remaining elements of L[], if there


# are any
while i < n1:
arr[k] = L[i]
i += 1
k += 1
while j < n2:
arr[k] = R[j]

14
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering
Poornima College of Engineering, Jaipur Department of Computer Engineering

j += 1
k += 1

# l is for left index and r is right index of the


# sub-array of arr to be sorted

def mergeSort(arr, l, r):


if l < r:

# Same as (l+r)//2, but avoids overflow for


# large l and h
m = l+(r-l)//2

# Sort first and second halves


mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)

# Driver code to test above


arr = [12, 11, 13, 5, 6, 7]
n = len(arr)
print("Given array is")
for i in range(n):
print("%d" % arr[i],end=" ")

mergeSort(arr, 0, n-1)
print("\n\nSorted array is")
for i in range(n):
print("%d" % arr[i],end=" ")

Output:

Given array is
12 11 13 5 6 7

Sorted array is
5 6 7 11 12 13

 Write a program to implement Selection sort, Insertion sort.

Program:

#Insertion Sort
a = [16, 19, 11, 15, 10, 12, 14]

15
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering
Poornima College of Engineering, Jaipur Department of Computer Engineering

for i in a:
j = a.index(i)
#i is not the first element
while j>0:
#not in order
if a[j-1] > a[j]:
#swap
a[j-1],a[j] = a[j],a[j-1]
else:
#in order
break
j = j-1
print (a)

#Selection Sort

a = [16, 19, 11, 15, 10, 12, 14]


i=0
while i<len(a):
#smallest element in the sublist
smallest = min(a[i:])
#index of smallest element
index_of_smallest = a.index(smallest)
#swapping
a[i],a[index_of_smallest] = a[index_of_smallest],a[i]
i=i+1
print (a)

Output:
[10, 11, 12, 14, 15, 16, 19]

[10, 11, 12, 14, 15, 16, 19]

16
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering
Poornima College of Engineering, Jaipur Department of Computer Engineering

Beyond the Syllabus Experiment-1

AIM: WAP to implement Heap Sort

Program:

def heapify(arr, N, i):


largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2

# See if left child of root exists and is


# greater than root
if l < N and arr[largest] < arr[l]:
largest = l

# See if right child of root exists and is


# greater than root
if r < N and arr[largest] < arr[r]:
largest = r

# Change root, if needed


if largest != i:
arr[i], arr[largest] = arr[largest], arr[i] # swap

# Heapify the root.


heapify(arr, N, largest)

# The main function to sort an array of given size

def heapSort(arr):
N = len(arr)

# Build a maxheap.
for i in range(N//2 - 1, -1, -1):
heapify(arr, N, i)

# One by one extract elements


for i in range(N-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)

17
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering
Poornima College of Engineering, Jaipur Department of Computer Engineering

# Driver's code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]

# Function call
heapSort(arr)
N = len(arr)

print("Sorted array is")


for i in range(N):
print("%d" % arr[i], end=" ")

Output:

Sorted array is
5 6 7 11 12 13

18
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering
Poornima College of Engineering, Jaipur Department of Computer Engineering

Beyond the Syllabus Experiment-2

AIM: WAP to implement Binary Tree

Program:

from binarytree import Node


root = Node(3)
root.left = Node(6)
root.right = Node(8)

# Getting binary tree


print('Binary tree :', root)

# Getting list of nodes


print('List of nodes :', list(root))

# Getting inorder of nodes


print('Inorder of nodes :', root.inorder)

# Checking tree properties


print('Size of tree :', root.size)
print('Height of tree :', root.height)

# Get all properties at once


print('Properties of tree : \n', root.properties)

Output:
Binary tree :
3
/\
68
List of nodes : [Node(3), Node(6), Node(8)]
Inorder of nodes : [Node(6), Node(3), Node(8)]
Size of tree : 3
Height of tree : 1
Properties of tree :
{‘height’: 1, ‘size’: 3, ‘is_max_heap’: False, ‘is_min_heap’: True,
‘is_perfect’: True, ‘is_strict’: True, ‘is_complete’: True,
‘leaf_count’: 2, ‘min_node_value’: 3, ‘max_node_value’: 8,
‘min_leaf_depth’: 1, ‘max_leaf_depth’: 1, ‘is_bst’: False,
‘is_balanced’: True, ‘is_symmetric’: False}
h

19
Python Lab (6CS4-23) Manual 2022-23 Department of Computer Engineering

You might also like