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

Python Prog Lab Manual KR21

The document provides information about Keshav Memorial Institute of Technology including its vision, mission, and details of the Computer Science and Engineering department. It lists the vision and mission statements of the institution and department. It also provides the index and list of experiments for a Python programming lab manual.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Python Prog Lab Manual KR21

The document provides information about Keshav Memorial Institute of Technology including its vision, mission, and details of the Computer Science and Engineering department. It lists the vision and mission statements of the institution and department. It also provides the index and list of experiments for a Python programming lab manual.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

(KMIT)

(Approved by AICTE, New Delhi and Affiliated to JNTUH)


Narayanaguda, Hyderabad – 500029

(Autonomous)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING (DS)

LAB MANUAL

PYTHON PROGRAMMING

B.Tech I YEAR II SEM (KR21 REGULATIONS)


ACADEMIC YEAR 2021-22

1
INDEX

S.NO TOPIC PAGE NO

I List of Experiments ii

II V/M /POs/PSOs/PEOs iv

III Syllabus ix

IV Course Objectives & Course Outcomes xi

i
List of Experiments

Exp No. Experiment Name Page No.


a) Arun is working in an office which is N blocks away from his house. He
wants to minimize the time it takes him to go from his house to the office.
He can either take the office cab or he can walk to the office. Arun's velocity
is V1 m/s when he is walking. The cab moves with velocity V2 m/s but
whenever he calls for the cab, it always starts from the office, covers N
blocks, collects Arun and goes back to the office. The cab crosses a total
distance of N meters when going from office to Arun's house and vice versa,
whereas Arun covers a distance of (√2)(2)*N while walking. Write a
program to help Arun to find whether he should walk or take a cab to
minimize the time.
1 1
b) There is a robot which wants to go the charging point to charge itself. The
robot moves in a 2-D plane from the original point (0,0). The robot can
move toward UP, DOWN, LEFT and RIGHT with given steps. The trace of
robot movement is shown as the following: UP 5 DOWN 3 LEFT 3 RIGHT
2 Then, the output of the program should be: 2 The numbers after the
direction are steps. Write a program to compute the distance between the
current position after a sequence of movement and original point. If the
distance is a float, then just print the nearest integer (use round() function
for that and then convert it into an integer).
a) Write a program that prints the numbers from 1 to 100. But for multiples of
three print “Fizz” instead of the number and for the multiples of five print
“Buzz”. For numbers which are multiples of both three and five print
“FizzBuzz”.
b) Write a program to check whether a given positive number is a Harshad
Number or not. A harshad number is an integer that is divisible by the sum
2 of its digits. For example 171 is a Harshad Number because the sum of 3
digits is 9(1+7+1) and 171 is divisible by 9.
c) Given a number n, write an efficient function to print all unique prime
factors of n. For example, if the input number is 315, then output should be
"3 5 7".
d) Given an integer number N, find whether it can be expressed as a sum of
two semi-primes or not (not necessarily distinct).
a) You are given a string which is a password, write a program to check if
3 the password entered by the user is a valid or not. If it is a valid password 8
then print “valid” else print “Invalid”

ii
b) Given a string S having characters from English alphabets ['a' - 'z'] and '.'
as the special character (without quotes). Write a program to construct the
lexicographically smallest palindrome by filling each of the faded character
('.') with a lower case alphabet.
c) Given an alphanumeric string S, write a program to extract maximum
numeric value from that string. All the alphabets are in lower case. Take the
maximum consecutive digits as a single number.
a) Given a list A of elements of length N, ranging from 0 to N-1. All
elements may not be present in the array. If the element is not present then
there will be -1 present in the array. Rearrange the array such that A[i] = i
and if i is not present then insert -1 at that place.
b) Given an array A of N numbers, you have to write a program which
4 prints the sum of the elements of array A with the corresponding elements of 12
the reverse of array A. If array A has elements [1,2,3], then reverse of the
array A will be [3,2,1] and the resultant array should be [4,4,4].
c) Given a list A of N distinct integers, write a program to sort the list by
moving an element to the end of the list. Find the minimum number of
moves required to sort the list using this method in ascending order.
a) A lower triangular matrix is a square matrix (where the number of rows
and columns are equal) where all the elements above the diagonal are zero.
Write a program to convert a given square matrix into a lower triangular
5 matrix. 15

b) Given a square matrix, write a program to print it in a counter-clockwise


spiral form.
a) Given a number n, define a function named printDict() which can print a
dictionary where the keys are numbers between 1 and n (both included) and
the values are square of keys. The function printDict() doesn't take any
6 argument. 18
b) Write a program to find the most common scores in the list of scores
given in sorted order based on occurrence from largest to smallest. If any of
scores are having same occurrence then consider the largest score first.
a) Write a program that loads roll numbers and names from the given CSV
file into dictionary where data is organized as one row per record. It takes a
roll number or name as input and prints the corresponding other value from
7 dictionary. 20
b) Write a program to find the frequency of distinct words in the given text
file and store the words along with the frequency in a CSV file.

iii
Import the iris dataset from https://archive.ics.uci.edu/ml/machine-learning-
databases/iris/iris.data
a) Find the mean, median, standard deviation of iris's ‘sepal length’ (1st
8 23
column).
b) Filter the rows of iris_2d that has petallength (3rd column) > 1.5
and sepallength (1st column) < 5.0
Import the Cars93 dataset into a data frame from
https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv
a) Check if dataframe has any missing values.
9 25
b) Count the number of missing values in each column of dataframe. Which
column has the maximum number of missing values?
c) Replace missing values in Min.Price and Max.Price columns with their
respective mean.
a) A number raised to the third power is a cube. Plot the first five cubic
10 numbers, and then plot the first 5000 cubic numbers. 29
b) Colored Cubes: Apply a colormap to your cubes plot.
Sitka is in a temperate rainforest, so it gets a fair amount of rainfall. In the
data file sitka_weather_2018_simple.csv is a header called PRCP, which
11 32
represents daily rainfall amounts. Make a visualization focusing on the data
in this column.

iv
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to
JNTUH) 3-5-1026, Narayanaguda, Hyderabad-29. Ph:
040-23261407

Department Of Computer Science & Engineering (DS)


Vision of the Institution:

To be the fountain head of latest technologies, producing highly skilled, globally competent
engineers.

Mission of the Institution:

• To provide a learning environment that inculcates problem solving skills, professional,


ethical responsibilities, lifelong learning through multi modal platforms and prepare students
to become successful professionals.

• To establish Industry Institute Interaction to make students ready for the industry.

• To provide exposure to students on latest hardware and software tools.

• To promote research based projects/activities in the emerging areas of technology


convergence.

• To encourage and enable students to not merely seek jobs from the industry but also to create
new enterprises

• To induce a spirit of nationalism which will enable the student to develop, understand India’s
challenges and to encourage them to develop effective solutions.

• To support the faculty to accelerate their learning curve to deliver excellent service to
students

v
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to
JNTUH) 3-5-1026, Narayanaguda, Hyderabad-29. Ph:
040-23261407

Department Of Computer Science & Engineering (DS)

Vision & Mission of Department


Vision of the Department:

To be among the region's premier teaching and research Computer Science and Engineering
departments producing globally competent and socially responsible graduates in the most
conducive academic environment.

Mission of the Department:

• To provide faculty with state of the art facilities for continuous professional development and
research, both in foundational aspects and of relevance to emerging computing trends.
• To impart skills that transform students to develop technical solutions for societal needs and
inculcate entrepreneurial talents.
• To inculcate an ability in students to pursue the advancement of knowledge in various
specializations of Computer Science and Engineering and make them industry-ready.
• To engage in collaborative research with academia and industry and generate adequate
resources for research activities for seamless transfer of knowledge resulting in sponsored
projects and consultancy.
• To cultivate responsibility through sharing of knowledge and innovative computing solutions
that benefit the society-at-large.
• To collaborate with academia, industry and community to set high standards in academic
excellence and in fulfilling societal responsibilities.

vi
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to
JNTUH) 3-5-1026, Narayanaguda, Hyderabad-29. Ph:
040-23261407

PROGRAM OUTCOMES (POs)

1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem Analysis: Identify, formulate, review research literature, and analyze 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, societal, and environmental
considerations.
4. Conduct Investigations of Complex Problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
5. Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.
6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice.
7. Environment and Sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
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.
11. Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long Learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.

vii
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to
JNTUH) 3-5-1026, Narayanaguda, Hyderabad-29. Ph:
040-23261407

Department of Computer Science & Engineering (DS)

PROGRAM SPECIFIC OUTCOMES (PSOs)


PSO1: An ability to analyze the common business functions to design and develop appropriate
Computer Science solutions for social upliftments.

PSO2: Shall have expertise on the evolving technologies like Python, Machine Learning, Deep
Learning, Internet of Things (IOT), Data Science, Full stack development, Social Networks,
Cyber Security, Big Data, Mobile Apps, CRM, ERP etc.

viii
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to
JNTUH) 3-5-1026, Narayanaguda, Hyderabad-29. Ph:
040-23261407

Department of Computer Science & Engineering (DS)

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)


PEO1: Graduates will have successful careers in computer related engineering fields or will be
able to successfully pursue advanced higher education degrees.

PEO2: Graduates will try and provide solutions to challenging problems in their profession by
applying computer engineering principles.

PEO3: Graduates will engage in life-long learning and professional development by rapidly
adapting changing work environment.

PEO4: Graduates will communicate effectively, work collaboratively and exhibit high levels of
professionalism and ethical responsibility.

ix
SYLLABUS
Python Programming Lab
B.TECH I Year II Sem
1. a) Arun is working in an office which is N blocks away from his house. He wants to
minimize the time it takes him to go from his house to the office. He can either take the
office cab or he can walk to the office. Arun's velocity is V1 m/s when he is walking. The
cab moves with velocity V2 m/s but whenever he calls for the cab, it always starts from the
office, covers N blocks, collects Arun and goes back to the office. The cab crosses a total
distance of N meters when going from office to Arun's house and vice versa, whereas Arun
covers a distance of (√2)(2)*N while walking. Write a program to help Arun to find whether
he should walk or take a cab to minimize the time.
b) There is a robot which wants to go the charging point to charge itself. The robot moves in
a 2-D plane from the original point (0,0). The robot can move toward UP, DOWN, LEFT and
RIGHT with given steps. The trace of robot movement is shown as the following: UP 5
DOWN 3 LEFT 3 RIGHT 2 Then, the output of the program should be: 2 The numbers after
the direction are steps. Write a program to compute the distance between the current position
after a sequence of movement and original point. If the distance is a float, then just print the
nearest integer (use round() function for that and then convert it into an integer).
2. a) Write a program that prints the numbers from 1 to 100. But for multiples of three
print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which
are multiples of both three and five print.
b) Write a program to check whether a given positive number is a Harshad Number or not. A
harshad number is an integer that is divisible by the sum of its digits. For example 171 is a
Harshad Number because the sum of digits is 9(1+7+1) and 171 is divisible by 9.
c) Given a number n, write an efficient function to print all unique prime factors of n. For
example, if the input number is 315, then output should be "3 5 7".
d) A semiprime number is an integer which can be expressed as a product of two distinct
primes. For example 15 = 3*5 is a semiprime number but 9 = 3*3 is not.
Given an integer number N, find whether it can be expressed as a sum of two semi-primes or
not (not necessarily distinct).
3. a) You are given a string which is a password, write a program to check if the password
entered by the user is a valid or not. If it is a valid password then print “valid” else print
“Invalid”
Rules of the password:
i) Minimum length is 6 characters and maximum length is 15 characters.
ii) It should have a minimum of one Capital Letter, One digit and one special symbol
iii) Special symbols allowed are only (*, @, #)

x
b) Given a string S having characters from English alphabets ['a' - 'z'] and '.' as the special
character (without quotes). Write a program to construct the lexicographically smallest
palindrome by filling each of the faded character ('.') with a lower case alphabet.
The smallest lexicographical order is an order relation where string s is smaller than t, given
the first character of s (s1) is smaller than the first character of t (t1), or in case they are
equivalent, the second character, etc.
c) Given an alphanumeric string S, write a program to extract maximum numeric value from
that string. All the alphabets are in lower case. Take the maximum consecutive digits as a
single number.
4. a) Given a list A of elements of length N, ranging from 0 to N-1. All elements may not be
present in the array. If the element is not present then there will be -1 present in the array.
Rearrange the array such that A[i] = i and if i is not present then insert -1 at that place.
b) Given an array A of N numbers, you have to write a program which prints the sum of the
elements of array A with the corresponding elements of the reverse of array A.
If array A has elements [1,2,3], then reverse of the array A will be [3,2,1] and the resultant
array should be [4,4,4].
c) Given a list A of N distinct integers, write a program to sort the list by moving an element
to the end of the list. Find the minimum number of moves required to sort the list using this
method in ascending order.
5. a) A lower triangular matrix is a square matrix (where the number of rows and columns are
equal) where all the elements above the diagonal are zero. Write a program to convert a
given square matrix into a lower triangular matrix.
b) Given a square matrix, write a program to print it in a counter-clockwise spiral form.
6. a) Given a number n, define a function named printDict() which can print a dictionary where
the keys are numbers between 1 and n (both included) and the values are square of keys. The
function printDict() doesn't take any argument.
b) Write a program to find the most common scores in the list of scores given in sorted order
based on occurrence from largest to smallest. If any of scores are having same occurrence
then consider the largest score first.
Input format: First line contains the list of scores and next line contains a number (k) which
represent the top most scores to display.
Output format: display the k top most scores.
7. a) Write a program that loads roll numbers and names from the given CSV file into
dictionary where data is organized as one row per record. It takes a roll number or name as
input and prints the corresponding other value from dictionary.
b) Write a program to find the frequency of distinct words in the given text file and store the
words along with the frequency in a CSV file.
xi
8. Import the iris dataset from https://archive.ics.uci.edu/ml/machine-learning-
databases/iris/iris.data
a) Find the mean, median, standard deviation of iris's ‘sepal length’ (1st column).
b) Filter the rows of iris_2d that has petallength (3rd column) > 1.5 and sepallength
(1st column) < 5.0
9. Import the Cars93 dataset into a data frame from
https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv
a) Check if dataframe has any missing values.
b) Count the number of missing values in each column of dataframe. Which column has the
maximum number of missing values?
c) Replace missing values in Min.Price and Max.Price columns with their respective mean.
10. a) A number raised to the third power is a cube. Plot the first five cubic numbers, and then
plot the first 5000 cubic numbers.
b) Colored Cubes: Apply a colormap to your cubes plot.
11. Sitka is in a temperate rainforest, so it gets a fair amount of rainfall. In the data file
sitka_weather_2018_simple.csv is a header called PRCP, which represents daily rainfall
amounts. Make a visualization focusing on the data in this column.

xii
Course Objectives: To learn
1. Understand the usage of data types, loops and conditional statements and functions.
2. Understand Lists, Dictionaries and Regular expressions in Python.
3. Handle Strings and Files in Python.
4. Learn the implantation of Python modules like Numpy, Pandas, matplotlib.

Course Outcomes: After learning the contents of this course the student is able to
CO1. Examine Python syntax and semantics and be fluent in the use of Python flow control and
functions. Demonstrate proficiency in handling Strings and File Systems.
CO2. Create, run and manipulate Python Programs using core data structures like Lists, Tuples,
and Dictionaries.
CO3. Implement exemplary applications related to Numpy, Pandas and matplotlib in Python.

CO VS PO MAPPING:
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

Python CO1 3 2 2 2 2 2
Programming
Lab CO2 3 2 3 2 3 3

CO3 3 3 3 3 3 3

CO VS PSO MAPPING:
PSO-1 PSO-2
CO1 1 3
CO2 2 3
CO3 2 3

xiii
Experiment 1
1 a) Arun is working in an office which is N blocks away from his house. He wants to
minimize the time it takes him to go from his house to the office. He can either take the
office cab or he can walk to the office. Arun’s velocity is V1 m/s when he is walking. The
cab moves with velocity V2 m/s but whenever he calls for the cab, it always starts from the
office, covers N blocks, collects Arun and goes back to the office. The cab crosses a total
distance of N meters when going from office to Arun’s house and vice versa, whereas Arun
covers a distance of (√2)*N while walking. Write a program to help Arun to find whether
he should walk or take a cab to minimize the time.
Program:
import math
N = int(input("Enter number of blocks: "))
V1 = int(input("Enter walking velocity: "))
V2 = int(input("Enter cab velocity: "))
Walk_time = math.sqrt(2)* N / V1
Cab_time = 2 * N / V2
if (Walk_time<Cab_time):
print("Walk")
else:
print("Cab")

Sample input & output 1:


Enter number of blocks: 2
Enter walking velocity: 10
Enter cab velocity: 14
Walk

Sample input & output 2:


Enter number of blocks: 5
Enter walking velocity: 10
Enter cab velocity: 15
Cab

1
1 b) There is a robot which wants to go the charging point to charge itself. The robot moves
in a 2-D plane from the original point (0,0). The robot can move toward UP, DOWN, LEFT
and RIGHT with given steps. The trace of robot movement is shown as the following: UP 5
DOWN 3 LEFT 3 RIGHT 2 Then, the output of the program should be: 2 The numbers
after the direction are steps. Write a program to compute the distance between the current
position after a sequence of movement and original point. If the distance is a float, then just
print the nearest integer (use round() function for that and then convert it into an integer).
Program:
from math import *
x,y=0,0
n=int(input())
for i in range(n):
d,m = input().split()
if d=="UP":
y=y+int(m)
elif d=="DOWN":
y=y-int(m)
elif d=="LEFT":
x=x-int(m)
else:
x=x+int(m)
dist = sqrt(x*x+y*y)
print("Distance=",round(dist))

Sample input & output:


4
UP 5
DOWN 3
LEFT 3
RIGHT 2
Distance= 2

2
Experiment 2
2 a) Write a program that prints the numbers from 1 to 100. But for multiples of three
print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers
which are multiples of both three and five print.
Program:

for i in range(1,101):
if(i%15==0):
print("FizzBuzz")
elif(i%5==0):
print("Buzz")
elif(i%3==0):
print("Fizz")
else:
print(i)
Sample Input & Output:
1 26 Fizz 76
2 Fizz 52 77
Fizz 28 53 Fizz
4 29 Fizz 79
Buzz FizzBuzz Buzz Buzz
Fizz 31 56 Fizz
7 32 Fizz 82
8 Fizz 58 83
Fizz 34 59 Fizz
Buzz Buzz FizzBuzz Buzz
11 Fizz 61 86
Fizz 37 62 Fizz
13 38 Fizz 88
14 Fizz 64 89
FizzBuzz Buzz Buzz FizzBuzz
16 41 Fizz 91
17 Fizz 67 92
Fizz 43 68 Fizz
19 44 Fizz 94
Buzz FizzBuzz Buzz Buzz
Fizz 46 71 Fizz
22 47 Fizz 97
23 Fizz 73 98
Fizz 49 74 Fizz
Buzz Buzz FizzBuzz Buzz

3
2 b) Write a program to check whether a given positive number is a Harshad Number or
not. A harshad number is an integer that is divisible by the sum of its digits. For example
171 is a Harshad Number because the sum of digits is 9(1+7+1) and 171 is divisible by 9.
Program:

n = int(input("Enter a positive number: "))


t=n
s=0
while(t>0):
d = t%10
s = s+d
t = t//10
if(n%s==0):
print(n,"is harshad number")
else:
print(n,"is not harshad number")

Sample Input & Output 1:


Enter a positive number: 408
408 is harshad number

Sample Input & Output 2:


Enter a positive number: 123
123 is not harshad number

4
2 c) Given a number n, write an efficient function to print all unique prime factors of n. For
example, if the input number is 315, then output should be "3 5 7".
Program:
def prime(num):
for j in range(2,num):
if(num%j==0):
return False
return True

def primeFactors(n):
for i in range(2,n+1):
if(n%i==0 and prime(i)):
print(i,end=" ")

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


print("Prime factors of",n,"are:")
primeFactors(n)

Sample Input & Output:


Enter a number: 75
Prime factors of 75 are:
35

5
2 d) A semiprime number is an integer which can be expressed as a product of two distinct
primes. For example 15 = 3*5 is a semiprime number but 9 = 3*3 is not.
Given an integer number N, find whether it can be expressed as a sum of two semi-primes
or not (not necessarily distinct).
Program:

import math
MAX=200
arr=[]
sprime=[False]*(MAX)

for i in range(2, MAX):


cnt, num, j = 0, i, 2
while cnt< 2 and j * j <= num:
while num % j == 0:
num /= j
cnt += 1
j += 1
if(num > 1):
cnt += 1
if(cnt == 2):
x=i
if (int(math.sqrt(x))**2) != x:
sprime[i] = True
arr.append(i)

n=int(input("Enter an integer: "))


i=0
ans=False
while(arr[i] <= n//2):
if sprime[n-arr[i]] == True:
ans=True

6
break
i=i+1

if(ans):
print(n,"is sum of two semi-primes")
else:
print(n,"is not sum of two semi-primes")

Sample input & output 1:


Enter an integer: 35
35 is sum of two semi-primes

Sample Input & Output 2:


Enter an integer: 18
18 is not sum of two semi-primes

7
Experiment 3
3 a) You are given a string which is a password, write a program to check if the password
entered by the user is a valid or not. If it is a valid password then print “valid” else print
“Invalid”
Rules of the password:
i) Minimum length is 6 characters and maximum length is 15 characters.
ii) It should have a minimum of one Capital Letter, One digit and one special symbol
iii) Special symbols allowed are only (*, @, #)

Program:
import re
password = input("Enter a password: ")
flag = 0
while True:
if (len(password)<6 and len(password)>15):
flag = -1
break
elif not re.search("[a-z]", password):
flag = -1
break
elif not re.search("[A-Z]", password):
flag = -1
break
elif not re.search("[0-9]", password):
flag = -1
break
elif not re.search("[*@#]", password):
flag = -1
break
elif re.search("\s", password):
flag = -1
break
else:

8
flag = 0
print("Valid Password")
break

if flag ==-1:
print("Not a Valid Password")

Sample Input & Output:


Enter a password: Kmit123@
Valid Password

Sample input & output 2:


Enter a password: kmit
Not a Valid Password

9
3 b) Given a string S having characters from English alphabets ['a' - 'z'] and '.' as the
special character (without quotes). Write a program to construct the lexicographically
smallest palindrome by filling each of the faded character ('.') with a lower case alphabet.
The smallest lexicographical order is an order relation where string s is smaller than t,
given the first character of s (s1) is smaller than the first character of t (t1), or in case they
are equivalent, the second character, etc.
Program:
s = input("Enter a string: ")
alpha = []

for i in range(97,123):
alpha.append(chr(i))
for c in alpha:
new = s.replace('.',c)
if new==new[::-1]:
print(new)
break
else:
print("Not possible to make the string as palindrome")

Sample Input & Output 1:


Enter a string: p.ep
peep

Sample Input & Output 2:


Enter a string: r.t
Not possible to make the string as palindrome

10
3 c) Given an alphanumeric string S, write a program to extract maximum numeric value
from that string. All the alphabets are in lower case. Take the maximum consecutive digits
as a single number.
Program:
def extractMaximum(s):
num, res = 0, 0
for i in range(len(s)):
if s[i] >= "0" and s[i] <= "9":
num = num * 10 + int(int(s[i]) - 0)
else:
res = max(res, num)
num = 0

return max(res, num)


s = input("Enter a string: ")
print(extractMaximum(s))

Sample Input & Output:


Enter a string: 23dsa43dsa98
98

11
Experiment 4
4 a) Given a list A of elements of length N, ranging from 0 to N-1. All elements may not be
present in the array. If the element is not present then there will be -1 present in the array.
Rearrange the array such that A[i] = i and if i is not present then insert -1 at that place.
Program:

def newarray(ar, n):


for i in range(n):
for j in range(n):
if (ar[j] == i):
ar[j], ar[i] = ar[i], ar[j]
for i in range(n):
if (ar[i] != i):
ar[i] = -1
print("Array after Rearranging")
for i in range(n):
print(ar[i], end = " ")
arr = [int(x) for x in input().split(",")]
n = len(arr)
newarray(arr, n);

Sample Input & Output:


1,-1,3,4,-1,5
Array after Rearranging
-1 1 -1 3 4 5

12
4 b) Given an array A of N numbers, you have to write a program which prints the sum of
the elements of array A with the corresponding elements of the reverse of array A.
If array A has elements [1,2,3], then reverse of the array A will be [3,2,1] and the resultant
array should be [4,4,4].

Program:
n = int(input("Enter N value: "))
array = input("Enter array elements: ")
list1 = list(map(int,array.split()))
list2 = list1[::-1]
print("Resultant Array:",end=" ")
for x in range(n):
print(list1[x]+list2[x],end=" ")

Sample Input & Output:


Enter N value: 4
Enter array elements: 4 6 8 2
Resultant Array: 6 14 14 6

13
4 c) Given a list A of N distinct integers, write a program to sort the list by moving an
element to the end of the list. Find the minimum number of moves required to sort the list
using this method in ascending order.
Program:

arr = input("Enter the elements: ")


A = [int(i) for i in arr.split(" ")]
sorted_list = A.copy()
sorted_list.sort()
count = 0
while(A != sorted_list):
for i in range(len(A)-1):
curent_index = A.index(sorted_list[i])
next_index = A.index(sorted_list[i+1])
if(curent_index > next_index):
x = A[next_index]
A.remove(x)
A.append(x)
count+=1
break
print("Number moves to sort the list:", count)

Sample Input & Output:


Enter the elements: 1 3 2 4 5
Number moves to sort the list: 3

14
Experiment 5
5 a) A lower triangular matrix is a square matrix (where the number of rows and columns
are equal) where all the elements above the diagonal are zero. Write a program to convert
a given square matrix into a lower triangular matrix.

Program:
n = int(input("Enter number of rows: "))
mat = []
print("Enter elements:")
for i in range(n):
mat.append(input().split())
for i in range(n):
for j in range(n):
if j>i:
mat[i][j]=0
print("Lower Triangular matrix:")
for row in mat:
print(*row)

Sample Input & Output:


Enter number of rows: 3
Enter elements:
789
465
312
Lower Triangular matrix:
700
460
312

15
5 b) Given a square matrix, write a program to print it in a counter-clockwise spiral form.

Program:
a = int(input("Enter number of rows: "))
mat=[]
print("Enter elements:")
for i in range(0,a):
l = list(map(int, input ().split ()))
mat.append(l)
m,n = a,a
k,l = 0,0
count = 0
total = a*a
print("Counter-clockwise spiral form:")
while (k < m and l < n) :
if (count == total) :
break

for i in range(k, m) :
print(mat[i][l], end=" ")
count += 1
l += 1

if (count == total) :
break

for i in range (l, n) :


print(mat[m - 1][i], end = " ")
count += 1
m -= 1

16
if (count == total) :
break

if (k < m) :
for i in range(m - 1, k - 1, -1) :
print(mat[i][n - 1], end = " ")
count += 1
n -= 1

if (count == total) :
break

if (l < n) :
for i in range(n - 1, l - 1, -1) :
print( mat[k][i], end = " ")
count += 1
k += 1

Sample Input & Output:


Enter number of rows: 4
Enter elements:
1234
5678
9 10 11 12
13 14 15 16
Counter-clockwise spiral form:
1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7

17
Experiment 6
6 a) Given a number n, define a function named printDict() which can print a dictionary
where the keys are numbers between 1 and n (both included) and the values are square of
keys. The function printDict() doesn't take any argument.

Program:
def printDict():
n = int(input("Enter a number: "))
d=dict()
for i in range(1,n+1):
d[i]=i**2
print("The resultant dictionary is")
print(d)

printDict()

Sample Input & Output:


Enter a number: 8
The resultant dictionary is
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

18
6 b) Write a program to find the most common scores in the list of scores given in sorted
order based on occurrence from largest to smallest. If any of scores are having same
occurrence then consider the largest score first.
Input format: First line contains the list of scores and next line contains a number (k)
which represent the top most scores to display.
Output format: display the k top most scores.

Program:
scores = [int(x) for x in input().split()]

k = int(input())

unique_scores = set(scores)

freq = dict()

for s in unique_scores:

freq[s] = scores.count(s)

freq2 = dict(sorted(freq.items(), reverse = True, key = lambda kv:(kv[1], kv[0])))

top_scores = list(freq2.keys())

print(*top_scores[:k])

Sample Input:
1222234788
4
Sample output:
2874

19
Experiment 7
7 a) Write a program that loads roll numbers and names from the given CSV file into
dictionary where data is organized as one row per record. It takes a roll number or name
as input and prints the corresponding other value from dictionary.

Program:
import csv

mydict = {}

with open('C:\\Users\\DELL\\Downloads\\students.csv', mode='r') as inp:

reader = csv.reader(inp)

dict_from_csv = {rows[0]:rows[1] for rows in reader}

n=input("Enter roll no to print name")

if n in dict_from_csv:

print("Name : %s" %dict.get(dict_from_csv,n))

else:

print("Enter valid roll no")

Sample input & output 1:

Enter roll no to print name: 19BD1A0521

Name : A NEELANJANA

Sample input & output 2:

Enter roll no to print name: 19BD1A0526

Name : BARLA GEETIKA PRAVEENKUMAR

Sample input & output 3:

Enter roll no to print name: 1234567

Enter valid roll no

20
7 b) Write a program to find the frequency of distinct words in the given text file and store
the words along with the frequency in a CSV file.
Program:
import re

import string

frequency = {}

document_text = open('C:\\Users\\DELL\\Downloads\\file.txt', 'r')

text_string = document_text.read().lower()

match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)

for word in match_pattern:

count = frequency.get(word,0)

frequency[word] = count + 1

frequency_list = frequency.keys()

for words in frequency_list:

print(words, frequency[words])

with open("C:\\Users\\DELL\\Downloads\\Output1.csv", "a") as csv:

csv.write("%s %d\n" % (words, frequency[words]))

Input Text file:

21
Output:

welcome 2

kmit 1

python 1

programming 1

lab 1

22
Experiment 8
Import the iris dataset from https://archive.ics.uci.edu/ml/machine-learning-
databases/iris/iris.data
8 a) Find the mean, median, standard deviation of iris's ‘sepal length’ (1st column).
Program:

import numpy as np

import pandas as pd

iris_2d=pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-
databases/iris/iris.data",header=None)

iris_2d.columns=['SpealLength','SpealWidth','PetalLength','PetalWidth','Species']

iris_2d.head()#print top 5 rows details

print("Mean of SpealLength ",iris_2d["SpealLength"].mean())

print("median of SpealLength ",iris_2d["SpealLength"].median())

print("standard deviation of SpealLength ",iris_2d["SpealLength"].std())

Sample input & output:

Mean of SpealLength 5.843333333333335

median of SpealLength 5.8

standard deviation of SpealLength 0.8280661279778629

23
8 b) Filter the rows of iris_2d that has petallength (3rd column) > 1.5 and sepallength
(1st column) < 5.0

url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'

iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])

condition = (iris_2d[:, 2] > 1.5) & (iris_2d[:, 0] < 5.0)

iris_2d[condition]

Sample input & output:

array([[4.8, 3.4, 1.6, 0.2],

[4.8, 3.4, 1.9, 0.2],

[4.7, 3.2, 1.6, 0.2],

[4.8, 3.1, 1.6, 0.2],

[4.9, 2.4, 3.3, 1. ],

[4.9, 2.5, 4.5, 1.7]])

24
Experiment 9
Import the Cars93 dataset into a data frame from
https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv
9 a) Check if dataframe has any missing values.
Program:
import pandas as pd
df=pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv")
df.isnull()

Sample input & output: True indicates null value

25
9 b) Count the number of missing values in each column of dataframe. Which column has
the maximum number of missing values?
Program:
print("Number of missing values in each column:")
print(df.isnull().sum())
print("Columnn with maximum null values : ", df.count().idxmin())

Sample output:
Number of missing values in each column:
Manufacturer 4
Model 1
Type 3
Min.Price 7
Price 2
Max.Price 5
MPG.city 9
MPG.highway 2
AirBags 6
DriveTrain 7
Cylinders 5
EngineSize 2
Horsepower 7
RPM 3
Rev.per.mile 6
Man.trans.avail 5
Fuel.tank.capacity 8
Passengers 2
Length 4
Wheelbase 1
Width 6
Turn.circle 5
Rear.seat.room 4

26
Luggage.room 19
Weight 7
Origin 5
Make 3
dtype: int64
Columnn with maximum null values : Luggage.room

27
9 c) Replace missing values in Min.Price and Max.Price columns with their respective mean.
Program:
df["Min.Price"].fillna(df["Min.Price"].mean())
df["Max.Price"].fillna(df["Max.Price"].mean())

Sample output:
0 12.900000
1 29.200000
2 25.900000
3 17.118605
4 17.118605
...
88 16.600000
89 17.600000
90 22.900000
91 21.800000
92 24.800000
Name: Min.Price, Length: 93, dtype: float64

0 18.800000
1 38.700000
2 32.300000
3 44.600000
4 21.459091
...
88 22.700000
89 22.400000
90 23.700000
91 23.500000
92 28.500000
Name: Max.Price, Length: 93, dtype: float64

28
Experiment 10
10 a) A number raised to the third power is a cube. Plot the first five cubic numbers, and
then plot the first 5000 cubic numbers.
Program
from matplotlib import pyplot as plt
x=[1,2,3,4,5]
x_cube = [1, 8, 27, 64, 125]
plt.scatter(x,x_cube)
plt.title("Cubes", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Cube of Value', fontsize=14)

Sample input & output

29
/*plot the first 5000 cubic numbers*/
Program
from matplotlib import pyplot as plt
ylist=list(range(5001))
y_cube = [y**3 for y in ylist]
plt.scatter(ylist,y_cube)
plt.title("Cubes", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Cube of Value', fontsize=14)
plt.tick_params(axis='both', labelsize=14)

Sample input & output:

30
10 b) Colored Cubes: Apply a colormap to your cubes plot.
Program
x_values = list(range(5001))
cubes = [x**3 for x in x_values]
plt.scatter(x_values, cubes, edgecolor='none', c=cubes, cmap=plt.cm.BuGn, s=40)
plt.title("Cubes", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Cube of Value', fontsize=14)
plt.tick_params(axis='both', labelsize=14)
plt.axis([0, 5100, 0, 5100**3])
plt.show()

Sample input & output

31
Experiment 11
Sitka is in a temperate rainforest, so it gets a fair amount of rainfall. In the data file
sitka_weather_2018_simple.csv is a header called PRCP, which represents daily rainfall
amounts. Make a visualization focusing on the data in this column.
Program
import matplotlib.pyplot as plt
import pandas as pd
url = 'https://raw.githubusercontent.com/ehmatthes/pcc_2e/master/chapter_16/the_csv_file_form
at/data/sitka_weather_2018_simple.csv'
df_sitka = pd.read_csv(url)
df_sitka['PRCP'].plot(kind="hist",bins=50,figsize=(6,4)) #histogram
df_sitka.plot(x='DATE', y='PRCP', kind='scatter',
figsize=(6,5),
title='RainFall in 2018') #scatter
df_sitka.boxplot(column='PRCP', by='TMAX', figsize=(10,6)) #boxplot
df_sitka[['DATE','PRCP']].groupby('DATE').mean().sort_values(by='PRCP', ascending=False).p
lot.bar(figsize=(10,6), rot=10, title='Average Rain fall in stations wrt DATE') #bargraph
df_sitka[['TMAX','PRCP']].groupby('TMAX').mean().sort_values(by='PRCP', ascending=False).
plot.bar(figsize=(10,6), rot=10, title='Average Rain fall in stations wrt DATE')
Sample input & output
1. histogram

32
2. scatter plot

3. boxplot

33
4. bar graph : DATE,PRCP

5.Bar graph: TMAX,PRCP

34

You might also like