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

Python Lab Manual Updated 2020-21

This lab manual contains 12 sections with Python code samples, inputs, and outputs that teach concepts like string manipulation, operators, loops, functions
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)
75 views

Python Lab Manual Updated 2020-21

This lab manual contains 12 sections with Python code samples, inputs, and outputs that teach concepts like string manipulation, operators, loops, functions
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/ 32

JSPM’s

Rajarshi Shahu College of Engineering


Tathawade, Pune - 033
Department of MCA
Lab Manual
Subject -: Python Programming Class -: MCA II Sem -: IV
__________________________________________________________________

1) WAP to demonstrate String Operations

Solution:

str = 'Hello World!'


print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
print str.upper()
print str.lower()
print len(str)

#####Output#####

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
HELLO WORLD!
hello world!
12
2) WAP to demonstrate Arithmatic,Comparision,Assignment,Bitwise
Operators

A) Arithmatic Operator
Solution:

a = 21
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c
c=a-b
print "Line 2 - Value of c is ", c
c=a*b
print "Line 3 - Value of c is ", c
c=a/b
print "Line 4 - Value of c is ", c
c=a%b
print "Line 5 - Value of c is ", c
a=2
b=3
c = a**b
print "Line 6 - Value of c is ", c
a = 10
b=5
c = a//b
print "Line 7 - Value of c is ", c

#####Output#####

Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2
B) Comparison Operator
Solution:

a = 21
b = 10
c=0
if ( a == b ):
print "Line 1 - a is equal to b"
else:
print "Line 1 - a is not equal to b"
if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b"
if ( a <> b ):
print "Line 3 - a is not equal to b"
else:
print "Line 3 - a is equal to b"
if ( a < b ):
print "Line 4 - a is less than b"
else:
print "Line 4 - a is not less than b"
if ( a > b ):
print "Line 5 - a is greater than b"
else:
print "Line 5 - a is not greater than b"
a = 5;
b = 20;
if ( a <= b ):
print "Line 6 - a is either less than or equal to b"
else:
print "Line 6 - a is neither less than nor equal to b"
if ( b >= a ):
print "Line 7 - b is either greater than or equal to b"
else:
print "Line 7 - b is neither greater than nor equal to b"

#####Output#####

Line 1 - a is not equal to b


Line 2 - a is not equal to b
Line 3 - a is not equal to b
Line 4 - a is not less than b
Line 5 - a is greater than b
Line 6 - a is either less than or equal to b
Line 7 - b is either greater than or equal to b

C) Assignment Operator
Solution:

a = 21
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c
c += a
print "Line 2 - Value of c is ", c
c *= a
print "Line 3 - Value of c is ", c
c /= a
print "Line 4 - Value of c is ", c
c =2
c %= a
print "Line 5 - Value of c is ", c
c **= a
print "Line 6 - Value of c is ", c
c //= a

#####Output#####

print "Line 7 - Value of c is ", c


Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
D) Bitwise Operator
Solution:

a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0

c = a & b; # 12 = 0000 1100


print "Line 1 - Value of c is ", c

c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c

c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c

c = ~a; # -61 = 1100 0011


print "Line 4 - Value of c is ", c

c = a << 2; # 240 = 1111 0000


print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c

#####Output#####

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
3) WAP to demonstrate Percision Operators

Solution:
a = 20
b = 10
c = 15
d=5
e=0

e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e

e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e

e = (a + b) * (c / d); # (30) * (15/5)


print "Value of (a + b) * (c / d) is ", e

e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e

#####Output#####

Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
4) WAP to demonstrate row input and input function to check given number
is prime or not

Solution:
def prime(n1,n2):
#n=int(input("enter a number:"))
for no in range(n1,n2):
for i in range(2,no):
if(no%i)==0:
break;
else:
print(no)

n1=int(input("enter range to display prime numbers in between"));


n2=int(raw_input("enter range to display prime numbers in between"));
print(prime(n1,n2))

#####Output#####

enter range to display prime numbers in between6


enter range to display prime numbers in between22
7
11
13
17
19
None
5)A) WAP for while loop

Solution:
count=0
while(count<6):
count=count+1
print count
#####Output#####
123456

5)B) WAP for Infinite while loop


Solution:

while True:
print("hello world")

#####Output#####
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world

5) C) WAP for for loop


Solution:
num=[2,4,6,8]
sum=0
for val in num:
sum=sum+val
print sum

#####Output#####
20
5)D) WAP for for loop with else statement
Solution:
for i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Break")

#####Output#####
1
2
3
No Break

6)A) WAP for call by value


Solution:

some_guy = 'Fred'

first_names = []
first_names.append(some_guy)

another_list_of_names = first_names
another_list_of_names.append('George')
some_guy = 'Bill'

print (some_guy, first_names, another_list_of_names)

#####Output#####

Bill ['Fred', 'George'] ['Fred', 'George']

6)B) Call By Reference


Solution:

def foo(bar):
bar.append(42)
print(bar)
answer_list = []
foo(answer_list)
print(answer_list)
#####Output#####

[42]
[42]

6)C) WAP for anonymous function


Solution:

sum=lambda arg1,arg2:arg1+arg2
print("Value of total:",sum(10,500))
output
Value of total: 510
12)WAP to calculate area of circle,triangle,rectangle
def area_circle(r):
pie=3.14
area=pie*r*r
return area
r=float(input("enter radius of circle:"))
print("Area of Circle is:",area_circle(r))
def ar_rec(l,b):
return l*b
def ar_triangle(b1,h):
return 0.5*b1*h
l=int(input("enter length:"))
b=int(input("enter breadth:"))
b1=int(input("enter base for traigle:"))
h=int(input("enter height for triangle:"))
print("Area of Rectangle is=",ar_rec(l,b))
print("Area of Triangle is=",ar_triangle(b1,h))

#####Output#####
enter radius of circle:12
Area of Circle is: 452.15999999999997
enter length:12
enter breadth:12
enter base for traigle:12
enter height for triangle:12
Area of Rectangle is= 144
Area of Triangle is= 72.0
7) WAP for String Built in functions
Solution:

str="welcome to jspm"
print(str.split())
str1="welcome to jspm mca department to get good \n job"
print(str1)
print(str1.splitlines())
str2="Nagesh"
print(str2.upper())
print(str2.isdigit())
print(str2.lower())
str3 = 'Hello Nagesh!'
print(str3)
print(str3[0])
print(str3[2:5])
print(str3[2:])
print(str3 * 2)

#####Output#####

['welcome', 'to', 'jspm']


welcome to jspm mca department to get good
job
['welcome to jspm mca department to get good ', ' job']
NAGESH
False
nagesh
Hello Nagesh!
H
llo
llo Nagesh!
Hello Nagesh!Hello Nagesh!
8) Write a program to capitalize first and last letter of given string.
Solution:

def cap(str):
str=str.capitalize()
s=str[-1:]
str=str[:-1]+str[-1].upper()
return str
print (cap("enter string"("dipu"));

#####Output#####
DipU

9) Write a program to replace the last three characters of string with 'ing',if
having 'ing' in the string then replace by 'ly'.
Solution:

def add_string(str1):
length=len(str1)

if length > 2:
if str1[-3:] == 'ing':
str1 +='ly'
else:
str1 +='ing'
return str1
print(add_string('ab'))
print(add_string('abc'))
print(add_string('string'))

#####Output#####

ab,abc,strly
10) Write a program to perform list operations.
Solution:

odd = [2, 4, 6, 8]
odd[0] = 1
my_list = ['p','r','o','g','r','a','m','i','z']
print(my_list[2:5])
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list.index(8))
print(my_list.count(8))
my_list.sort()
print(my_list)
my_list.reverse(), 6, 4, 3, 1, 0]
print(my_list)

#####Output#####

1
2
[0, 1, 3, 4, 6, 8, 8]
['r','o','b','l','e','m']

11) Write a program for list built in functions.


Solution:

List = ['Mathematics', 'chemistry', 1997, 2000]


List.append(20544)
print(List)
List = ['Mathematics', 'chemistry', 1997, 2000]
List.insert(2,10087)
print(List)
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
List1.extend(List2)
print(List1)
List2.extend(List1)
print(List2)
List = [1, 2, 3, 4, 5]
print(sum(List))
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(List))
#####Output#####

['Mathematics', 'chemistry', 1997, 2000, 20544]


['Mathematics', 'chemistry', 10087, 1997, 2000, 20544]
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
15
10

12) Write a program for list BuiltIn functions.


Solution:

list1, list2 = [123, 'xyz'], [456, 'abc']


print cmp(list1, list2)
print cmp(list2, list1)
list3 = list2 + [786];
print cmp(list2, list3)
list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
print "First list length : ", len(list1)
print "Second list length : ", len(list2)
list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
print "Max value element : ", max(list1)
print "Max value element : ", max(list2)
list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
print "min value element : ", min(list1)
print "min value element : ", min(list2)
aTuple = (123, 'xyz', 'zara', 'abc');
aList = list(aTuple)
print "List elements : ", aList

#####Output#####
-1,1,-1
First list length : 3,Second list length : 2
Max value element : zara,Max value element : 700
min value element : 123,min value element : 200
List elements : [123, 'xyz', 'zara', 'abc']
13) Write a program for list-comprehension using for loop,if statement,nested
loop
solution:

h_letters = []
for letter in 'human':
h_letters.append(letter)
print(h_letters)

#Nested loop
transposed = []
matrix = [[1, 2, 3, 4], [4, 5, 6, 8]]
for i in range(len(matrix[0])):
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
print(transposed)
number_list = [ x for x in range(20) if x % 2 == 0]
print(number_list)

#####Output#####

['h', 'u', 'm', 'a', 'n']


[[1, 4], [2, 5], [3, 6]]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
14) Write a program for tuple operations.
Solution:

my_tuple = (1, 2, 3)
print(my_tuple)
print(my_tuple[0])
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[-1])
print(my_tuple[1:4])
del my_tuple
my_tuple

#####Output#####
(1, 2, 3)
1
't'
'e','r','m'

15) Write a program for set operations.


Solution:

# sets are define


A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};
# union
print("Union :", A | B)
# intersection
print("Intersection :", A & B)
# difference
print("Difference :", A - B)
# symmetric difference
print("Symmetric difference :", A ^ B)

#####Output#####

('Union :', set([0, 1, 2, 3, 4, 5, 6, 8]))


('Intersection :', set([2, 4]))
('Difference :', set([8, 0, 6])
('Symmetric difference :', set([0, 1, 3, 5, 6, 8]))
16) Write a program to demonstrate dictionary operations to import module
using from keyword.
solution:

my_dict = {'name':'Jack', 'age': 26}


print(my_dict['name'])
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares.pop(4))
# remove all items
squares.clear()
# delete the dictionary itself
del squares
# import only pi from math module
from math import pi
print("The value of pi is", pi)

#####Output#####
Jack
{'age': 27, 'name': 'Jack'}
{'address': 'Downtown', 'age': 27, 'name': 'Jack'}
16
The value of pi is 3.141592653589793
17) Write a program to create User defined package,subpackage mypack.
solution:

#untitledpack
#__init__.py

#add.py
def add(x,y):
sum = x + y
return sum

#sub.py
def sub(x,y):
sub = x - y
return sub

#multi.py
def multi(x,y):
multi = x * y
return multi

#div.py
def div(x,y):
div = x / y
return div

#test.py

import sys
sys.path.append('C:\\Users\\admin\\PycharmProjects')
import untitled1
print(untitled1.add(10, 20))
print(untitled1.sub(10, 20))
print(untitled1.multi(10, 20))
print(untitled1.div(10, 20))
print(untitled1.squareroot(16))
print(untitled1.fib(5))
#sub mypack
#fib.py
def fib(n):
a, b = 0, 1
print(a)
while b < n:
print(b)
a, b = b, a + b

#sqrt.py
import math
def squareroot(n):
return math.sqrt(n)

#####Output#####

30,-10,200,0.5,4.0,0,1,1,2,3

18) Write a program Reading and Writing file.


Solution:

file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes
file1 = open("myfile.txt","r+")
print "Output of Read function is "
print file1.read()

#####Output#####

Hello
This is Delhi
This is Paris
This is London
19) Write a program Reading and Writing into Binary file.
Solution:

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
#read a file
def __init__(self, fileName):
self.file = open(fileName, 'rb')

20) Write a program to create text file.


Solution:
file = open(“testfile.txt”,”w”)
file.write(“Hello World”)
file.write(“This is our new text file”)
file.write(“and this is another line.”)
file.write(“Why? Because we can.”)
file.close()

21) Wrie a python code to diplay first m and last n lines from text file.
Solution:

def read_last_lines(filename, lines):


with open(filename, "r") as text_file:
contents = text_file.readlines()[-lines:]
for line in contents:
print(line, end="")
print("\n")
read_last_lines("text.txt", 2)

def read_first_lines(filename, lines):


with open(filename, "r") as text_file:
contents = text_file.readlines()[+lines:]
for line in contents[0:3]:
print(line,end="")
read_first_lines("text.txt", 0)
#####Output#####
gen3
gen 4
this is a text file
has a genereation of the whole computers
gen1

22) Write a program for assertion, try-except,finally block.


Solution:

1. Assertion

def kelvinToFahrenheit(Temperature):
assert(Temperature>=0),"colder than absolute zero"
return((Temperature-273)*1.8)+32
print(kelvinToFahrenheit(273))
print(kelvinToFahrenheit(505.73))
print(kelvinToFahrenheit(-4))

#####Output#####
32.0
450.91400000000004
Traceback (most recent call last):
File "D:\Harshada171816\exception.py", line 7, in <module>
print(kelvinToFahrenheit(-4))
File "D:\Harshada171816\exception.py", line 3, in kelvinToFahrenheit
assert(Temperature>=0),"colder than absolute zero"
AssertionError: colder than absolute zero

2. try-except:

try:
fh=open("textfile","w")
try:
fh.write("this is my test file for exception handling")
finally:
print("going to close the file")
fh.close()
except:
print("error cant find file or read data")

#####Output#####

going to close the file

23) Write a program to create user defined exceptino not prime if given
number is not prime else print the prime number
Solution:

class Error(Exception):
""" base class for exception """
pass
class NotPrimeNumber(Error):
"""raised when number is not prime"""
pass
n=int(input("enter a number:"))
for i in range(2,n):
try:
if n%i==0:
raise NotPrimeNumber
#else:
#print("number is prime")
#break
except NotPrimeNumber:
print("this number is not a prime number")
break

print("the number is prime number")

#####Output#####

enter a number:4
this number is not a prime number
24) Write a program to guess correct no that is 10 and throw user defined
exception Toosmallnumber if number is small and throw exception
Toolargenumber if entered number is large.
Solution:

class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""RAised when input is too small"""
pass
class ValueTooLargeError(Error):
"""raised when input value is too large"""
pass
#our program
number=10
while True:
try:
i_num=int(input("enter a no:"))
if i_num<number:
raise ValueTooSmallError
elif i_num>number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("this value is too small,try again!!!")
print()
except ValueTooLargeError:
print("this value is too large,try again!!!")
print("congratulations! you guessed it correctly")

#####Output#####

enter a no:4
this value is too small,try again!!!

enter a no:12
this value is too large,try again!!!
enter a no:10
congratulations! you guessed it correctly
25) Write a program to demonstrate class and object to create employee class
Solution:

#introduction to object oriented concepts


class Employee:
'Common base class for all employees'
empCount = 0

def __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print ("Total Employee %d" % Employee.empCount)

def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)

#This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
#This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
emp1.displayCount()
print ("Total Employee %d" % Employee.empCount)
e=emp1.age=7
print(e)
emp1.age=8
print(hasattr(emp1,'age'))
print(getattr(emp1,'age'))
setattr(emp1,'age',9)
print(getattr(emp1,'age'))
#delattr(em1,'age')
del emp1.age
#####Output#####
Name : Zara , Salary: 2000
Name : Manni , Salary: 5000
Total Employee 2
Total Employee 2
7
True
8
9

26) Write a program for python constructor and destructor


Solution:

class Point:
def __init__(self,x=0,y=0):
self.x=x;
self.y=y;

def __del__(self):
class_name=self.__class__.__name__
print(class_name,"destroyed")

pt1=Point()
pt2=pt1
pt3=pt1
print(id(pt1),id(pt2),id(pt3))
del pt1
del pt2
del pt3
#####Output#####

34951088 34951088 34951088


Point destroyed
27) Write a python code to demonstrate multiple and multilevel inheritance
A) Multiple inheritance
Solution:

#multiple inheritance
class person:
def __init__(self,personName,personAge):
self.name=personName
self.age=personAge
def showName(self):
print(self.name)
def showAge(self):
print(self.age)
class student:
def __init__(self,studentId):
self.studentId=studentId
def getId(self):
return self.studentId
class Resident(person,student):
def __init__(self,name,age,id):
person.__init__(self,name,age)
student.__init__(self,id)
r=Resident('john',30,'102')
r.showName()
r.showAge()
print(r.getId())

#####Output#####
john
30
102

27)B) Multilevel Inheritance


Solution:

#multilevel inheritance
class student:
def getStudent(self):
self.name=input("name:")
self.age=input("age:")
self.gender=input("Gender:")
class test(student):
def getMarks(self):
self.stuclass=input("class:")
print("enter marks of respective subjects:")
self.literature=int(input("literature:"))
self.math=int(input("math:"))
self.biology=int(input("biology:"))
self.physics=int(input("physics:"))
class Marks(test):
def display(self):
print("name:",self.name)
print("age:",self.age)
print("gender:",self.gender)
print("class:",self.stuclass)
print("total marks:",self.literature+self.math+self.biology+self.physics)
m1=Marks()
m1.getStudent()
m1.getMarks()
m1.display()
#####Output#####

name:harshada
age:22
Gender:female
class:mca
enter marks of respective subjects:
literature:66
math:66
biology:66
physics:66
name: harshada
age: 22
gender: female
class: mca
total marks: 264
28) Write a program to demonstrate class variable, data hiding, method
overriding and operator overloading
1. Class variable
2. Data hiding
Solution

#data hiding
class justCounter:
__secretCount=0
def count(self):
self.__secretCount+=1
print(self.__secretCount)
counter=justCounter()
counter.count()
counter.count()
#print(counter.__secretCount)
print(counter.__justCounter.__secretCount)
#object.__className_attrName

#####Output#####
1
2

3. Method Overriding
Solution:

#overriding

class parent:
def myMethod(self):
print("calling parent method")
class child(parent):
def myMethod(self):
print("calling child method")
c=child()
c.myMethod()
output: calling child method
4.operator overloading
==>#operator overloading
class vector:
def __init__(self,a,b):
self.a=a
self.b=b
def __str__(self):
return "vector(%d,%d)"%(self.a,self.b)
def __add__(self,other):
return (self.a+other.a,self.b+other.b)
v1=vector(2,10)
v2=vector(5,-2)
print(v1+v2)

#####Output#####
(7, 8)

29) Write a program to validate email address and mobile number using
regular expression.
1) Validate email address
Solution:

import re
email="harsha@gmail.com seemagmail.com rasika@gmail.com
himanshu@gmail.com"
print("email matches:",len(re.findall("[\w._%+-0-9]{1,20}@[\w.-]{2,20}.[A-Za-z]
{2,3}",email)))

#####Output#####
email matches: 3

2) Validate mobile number


Solution:

import re
#phone no validation
#\w=[a-zA-Z0-9]
#\W=[^a-zA-Z0-9]
pnum="91-9623608400"
if re.search("\w{2}-\w{10}",pnum):
print("this is valid phone number")

#####Output#####
this is valid phone number

30) Write a program to search string using given pattern and replace that
string by your first name using regular expression.
Solution:

import re
food="haf raf maf haf"
regex=re.compile("[r]af")
Food=regex.sub("Harshada",food)
print(Food)

#####Output#####
haf Harshada maf haf

31) Write a program to search name and age from given data
Solution:

#regular expressions
import re
Nameage='''Harshada is 23 , Rasika is 22,sneha is 23 , seema is 22'''
ages=re.findall(r'\d{1,4}',Nameage)
names=re.findall(r'[A-Z][a-z]*',Nameage)
ageDict={}
x=0
for eachname in names:
ageDict[eachname]=ages[x]
x+=1
print(ageDict)

#####Output#####

{'Harshada': '23', 'Rasika': '22'}


32) Write a program to create iterator using regular expression
Solution

import re
str="sat,mat,pat,hat"
allstr=re.findall("[shm]at",str);
for i in allstr:
print(i);
somestr=re.findall("[h-m]at",str);
for i in somestr:
print(i);
somestr1=re.findall("[^h-m]at",str)
for i in somestr1:
print(i);
food="hat,rat,mat,hat";
regex=re.compile("[r]at");
food=regex.sub("food",food);
print(food);

#####Output#####
sat
mat
hat
mat
hat
sat
pat
hat,food,mat,hat
33) Write a program for addition of matrix and transpose of matrix using list
comprehention.
Solution

X = [[1,2,3],
[7 ,8,9]]

Y = [[7,5,7],
[3,2,1]]

result = [[0,0,0],
[0,0,0]]

for i in range(len(X)):

for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)

#transpose of matrix using list comprehension


matrix=[[1,2],[3,4],[5,6],[7,8]]
transpose=[[row[i] for row in matrix] for i in range(2)]
print(transpose)

#####Output#####

[8, 7, 10]
[10, 10, 10]
[[1, 3, 5, 7], [2, 4, 6, 8]]

You might also like