Jobanpy

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 47

Assignment-1

1.1 WAP to display the pattern of numbers given as


follows: 1
12
123
1234
123
12
1

n=4

for i in range(1,

n+1): for j in

range(1, i+1): print(j,

end=" ") print()

for i in range(n - 1, 0, -1):

for j in range(1, i + 1):

print(j, end=" ")

print()

Output:
1.2 Given two lists, both having String elements, write a python program
using python lists to create a new string as per the rule given below:
The first element in list1 should be merged with last element in list2, second
element in list1 should be merged with second last element in list2 and so on. If
an element in list1/list2 is None, then the corresponding element in the other list
should be kept as it is in the merged list.

list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']

list2=['y','tor','e','eps','ay',None,'le','n']

a=len(list1)

ans=""

for i in range(0,len(list1)):

c=a-i-1

if(list1[i]==None):

word=list2[c]

elif(list2[c]==None):

word=list1[i]

else:

word=list1[i]+list2[c]

ans+=" "

ans+=word

print(ans)

Output:

1.3 Given a string containing uppercase characters (A-Z), compress the string
using Run Length encoding. Repetition of character has to be replaced by
storing the length of that run.Write a python function which performs the run
length

2
encoding for a given String and returns the run length encoded String. Provide
different String values and test your program.

Sample Input Expected Output

AAAABBBBCCCCCCCC 4A4B8C

AABCCA 2A1B2C1A

def run_length_encode(s):

if not s:

return ""

encoded = ""

count = 1

for i in range(1, len(s)):

if s[i] == s[i - 1]:

count += 1

else:

encoded += str(count) + s[i - 1]

count = 1

encoded +=str(count)+s[-1]

return encoded

input_string1 = "AAAABBBBCCCCCCCC"

input_string2 = "AABCCA"

result1 = run_length_encode(input_string1)

result2 = run_length_encode(input_string2)

print(f"Input: {input_string1}, Encoded: {result1}")

print(f"Input: {input_string2}, Encoded: {result2}")

3
Output:

1.4 A teacher is in the process of generating few reports based on the marks
scored by the students of her class in a project based assessment. Assume
that the marks of her 10 students are available in a tuple. The marks are out of
25.
Write a python program to implement the following functions:

find_more_than_average(): Find and return the percentage of students who have


scored more than the average mark of the class.
generate_frequency(): Find how many students have scored the same marks. For
example, how many have scored 0, how many have scored 1, how many have
scored 3….how many have scored 25. The result should be populated in a list and
returned.
sort_marks(): Sort the marks in the increasing order from 0 to 25. The sorted
values should be populated in a list and returned.

class StudentMarks:

def init (self, marks):

self.marks = marks

def find_more_than_average(self):

total_marks = sum(self.marks)

average_mark = total_marks / len(self.marks)

above_average = [mark for mark in self.marks if mark > average_mark]

percentage_above_average = (len(above_average) / len(self.marks)) * 100

return percentage_above_average

def generate_frequency(self):

frequency = [0] * 26

for mark in self.marks:

4
frequency[mark] += 1

return frequency

def sort_marks(self):

sorted_marks = sorted(self.marks)

return sorted_marks

# Example usage:

student_marks = (20, 15, 22, 18, 25, 12, 20, 8, 23, 17)

student_data = StudentMarks(student_marks)

percentage_above_average = student_data.find_more_than_average()

print(f"Percentage of students with marks above average: {percentage_above_average}%")

frequency = student_data.generate_frequency()

print("Frequency of marks:")

l=[*range(1,26)]

print(l)

print(frequency)

sorted_marks = student_data.sort_marks()

print("Sorted marks:", sorted_marks)

Output:

1.5 Consider sample data as follows: sample_data=range(1,11). Create two


functions: odd() and even(). The function even() returns a list of all the even
numbers from sample_data. The function odd() returns a list of all the odd
numbers from sample_data. Create a function sum_of_numbers() which
will accept the sample data and/or a function. If a function is not passed,
the
5
sum_of_numbers() should return the sum of all the numbers from sample_data. If
a function is passed, the sum_of_numbers() should return the sum of numbers
returned from the function passed.

def odd():

sample_data = range(1, 11)

return [x for x in sample_data if x % 2 != 0]

def even():

sample_data = range(1, 11)

return [x for x in sample_data if x % 2 == 0]

def sum_of_numbers(func=None):

sample_data = range(1, 11)

if func is None:

return sum(sample_data)

else:

numbers = func()

return sum(numbers)

# Example usage:

print("Sum of all numbers from sample_data:", sum_of_numbers())

even_sum = sum_of_numbers(even)

print("Sum of even numbers from sample_data:", even_sum)

odd_sum = sum_of_numbers(odd)

print("Sum of odd numbers from sample_data:", odd_sum)

Output:

6
1.6 Write a python function, check_anagram() which accepts two strings and
returns True, if one string is an anagram of another string. Otherwise
returns False.
The two strings are considered to be an anagram if they contain repeating
characters but none of the characters repeat at the same position. The length of
the strings should be the same.

Note: Perform case insensitive comparison wherever applicable.

Sample Input Expected Output

eat, tea True

backward,drawback False
(Reason: character
'a' repeats at position
6, not an anagram)

Reductions,discounter True

About, table False

def check_anagram(str1,str2):

str1 = str1.replace(" ", "").lower()

str2 = str2.replace(" ", "").lower()

if(len(str1)!=len(str2)):

return False

for x in str1:

if x not in str2:

return False

for i in range(0,len(str1)):

7
if(str1[i]==str2[i]):

return False

return True

print(check_anagram("reductions","discounter"))

print(check_anagram("backward","drawback"))

Output:

8
Assignment -2
2.1 Say you have a list of lists where each value in the inner lists is a
one-character string, like this:

grid = [['.', '.', '.', '.', '.', '.'],


['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
You can think of grid[x][y] as being the character at the x- and y-coordinates
of a “picture” drawn with text characters. The (0, 0) origin will be in the
upper-left corner, the x-coordinates increase going right, and the
y-coordinates increase going down. Copy the previous grid value, and write
code that uses it to print the image.
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....

list1 = [['.', '.', '.', '.', '.', '.'],

['.', 'O', 'O', '.', '.', '.'],

['O', 'O', 'O', 'O', '.', '.'],

['O', 'O', 'O', 'O', 'O', '.'],

['.', 'O', 'O', 'O', 'O', 'O'],

['O', 'O', 'O', 'O', 'O', '.'],

['O', 'O', 'O', 'O', '.', '.'],

['.', 'O', 'O', '.', '.', '.'],

['.', '.', '.', '.', '.', '.']]

9
for y in range(len(list1[0])):

for x in range(len(list1)):

print(list1[x][y], end='')

print()

2.2 Write a python program which finds the maximum number from num1 to
num2 (num2 inclusive) based on the following rules.

1. Always num1 should be less than num2


2. Consider each number from num1 to num2 (num2 inclusive). Populate
the number into a list, if the below conditions are satisfied
a. Sum of the digits of the number is a multiple of 3
b. Number has only two digits
c. Number is a multiple of 5
3. Display the maximum element from the list
4. In case of any invalid data or if the list is empty, display -1.

def digit_sum(n):

return sum(int(digit) for digit in str(n))

def find_max_num(num1, num2):

if num1 >= num2:

return -1

valid_numbers = [num for num in range(num1, num2 + 1) if digit_sum(num) % 3 == 0 and


len(str(num)) == 2 and num % 5 == 0]

if not valid_numbers:

return -1

return max(valid_numbers)

10
# Example usage:

num1 = 10

num2 = 99

result = find_max_num(num1, num2)

print(f"The maximum number meeting the conditions is: {result}")

Output:

2.3 Write a python program to generate the ticket numbers for specified
number of passengers travelling in a flight as per the details mentioned below:
The ticket number should be generated as airline:src:dest:number
where

1. Consider AI as the value for airline


2. src and dest should be the first three characters of the source
and destination cities.
3. number should be auto-generated starting from 101
4. The program should return the list of ticket numbers of last
five passengers.

Note: If passenger count is less than 5, return the list of all generated ticket
numbers.

import random

c=int(input("enter no of passengers"))

tn=''

ai="AI"

tns=[0]*c

for i in range(0,c):

tn=''

src=input("enter source")

11
des=input("enter destination")

num=random.randint(101,999)

tn=ai+":"+Dsrc[0:3]+":"+des[0:3]+":"+str(num)

tns[i]=tn

if (len(tns)<5):

print(tns)

else:

print(tns[-5:-1])

Output:

2.4 Write a Python program to categorize all the elements of a given tuple
according to their data type. Store the results of each category into a
new sub-tuple. Display the sorted order of each sub-tuple.

def categorize_elements(input_tuple):

result = {

'integers': tuple(sorted([elem for elem in input_tuple if isinstance(elem, int)])),

'floats': tuple(sorted([elem for elem in input_tuple if isinstance(elem, float)])),

'strings': tuple(sorted([elem for elem in input_tuple if isinstance(elem, str)])),

'booleans': tuple(sorted([elem for elem in input_tuple if isinstance(elem, bool)])),

return result

# Example usage:

12
given_tuple = (5, 3.14, 'apple', True, 'banana', 7, False, 2.718, 'cherry', 10)

result = categorize_elements(given_tuple)

for category, elements in result.items():

print(f"{category.capitalize()}: {elements}")

Output:

2.5 Care hospital wants to know the medical speciality visited by the
maximum number of patients. Assume that the patient id of the patient along
with the medical speciality visited by the patient is stored in a list. The details
of the medical specialities are stored in a dictionary as follows:
{
"P":"Pediatrics",
"O":"Orthopedics",
"E":"ENT
}
Write a function to find the medical speciality visited by the maximum number of
patients and return the name of the speciality.

Note:

1. Assume that there is always only one medical speciality which is visited
by maximum number of patients.
2. Perform case sensitive string comparison wherever necessary.

med_spec={"P":"Pediatrics","O":"Orthopedics","E":"ENT"}

np=int(input("enter no of patients"))

l=[0]*(np*2)

for i in range(0,len(l),2):

l[i]=int(input("enter patient id:"))

l[i+1]=(input("enter medspec:"))

13
p=l.count("P")

o=l.count("O")

e=l.count("E")

print(l)

if p>o:

if p>e:

print(med_spec["P"])

else:

print(med_spec["E"])

else:

if o>e:

print(med_spec["O"])

else:

print(med_spec["E"])

Output:

2.6 Write a python function, find_correct() which accepts a dictionary and


returns a list as per the rules mentioned below. The input dictionary will contain
correct spelling of a word as key and the spelling provided by a contestant as
the value. The function should identify the degree of correctness as mentioned
below: CORRECT, if it is an exact match
ALMOST CORRECT, if no more than 2 letters are wrong

14
WRONG, if more than 2 letters are wrong or if length (correct spelling versus
spelling given by contestant) mismatches.
and return a list containing the number of CORRECT answers, number of
ALMOST CORRECT answers and number of WRONG answers.
Assume that the words contain only uppercase letters and the maximum word
length is 10.

def find_correct(d):

k=list(d.keys())

v=list(d.values())

c=0

w=0

ac=0

for i in range(0,len(k)):

if((k[i])==(v[i])):

c=c+1 if(len(k[i])!

=len(v[i])):

w=w+1

if(len(k[i])==len(v[i]) and k[i])!=(v[i]):

c1=0

for j in range(0,len(k[i])):

if(((k[i])[j])!=((v[i])[j])):

15
c1=c1+1

if(c1>2):

w=w+1

else:

ac=ac+1

l=[c,ac,w]

print(l)

D={"THEIR": "THEIR", "BUSINESS":


"BISINESS","WINDOWS":"WINDMILL","WERE":"WEAR","SAMPLE":"SAMPLE"}

find_correct(D)

Output:

16
Assignment-3

3.1 Write a python program to compute the area of circle, square, and rectangle
using module.

Create a file named shapes.py

import math

def circle_area(radius):

return math.pi * radius ** 2

def square_area(side):

return side ** 2

def rectangle_area(length, width):

return length * width

Then, in another Python file, you can import this module and use its functions to compute the
areas:

import shapes

# Circle

radius = 5

circle_area = shapes.circle_area(radius)

print(f"Area of the circle with radius {radius} is: {circle_area:.2f}")

# Square

17
side_length = 7

square_area = shapes.square_area(side_length)

print(f"Area of the square with side {side_length} is: {square_area}")

# Rectangle

length = 4

width = 6

rectangle_area = shapes.rectangle_area(length, width)

print(f"Area of the rectangle with length {length} and width {width} is: {rectangle_area}")

Output:

3.2 Write a python program to calculate the frequency of vowels and


consonants in file

Contents of file :

18
Code:

f=open('crab.txt','r')

v=0

c=0

while True:

line=f.readline()

if not line:

break

else:

for x in line:

if x.lower()in 'aieou':

v=v+1

else:

c=c+1

print(c)

print(v)

Output:

19
3.3 Write a python program to swap the first and second half of the input
file content.

Contents of input file:

Code:

with open('input.txt', 'r') as file:

content = file.read()

length = len(content)

if length % 2 != 0:

print("Error: The input file content length must be even.")

else:

half1 = content[:length // 2]

half2 = content[length // 2:]

swapped_content = half2 + half1

with open('output.txt', 'w') as file:

file.write(swapped_content)

Contents of Output file:

20
3.4 Write a program to copy lines which start with a lowercase letter only from
the input file Demo.txt and ignore the lines which start from with an uppercase
letter. The output file Demo2.txt should contain only those lines from the file
Demo.txt which start with a lowercase letter.

Contents of Demo.txt:

Code:

with open('crab.txt', 'r') as file:

lines = file.readlines()

with open('demo2.txt', "w") as file:

for line in lines:

if line[0].islower():

file.write(line)

Output:

21
3.5 Create a Mad Libs program that reads in text files and lets the user add
their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB
appears in the text file. For example, a text file may look like this:

The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
unaffected by these events.
The program would find these occurrences and prompt the user to replace them.
Enter an adjective:
silly
Enter a noun:
chandelier
Enter a verb:
screamed
Enter a noun:
pickup truck
The following text file would then be created:
The silly panda walked to the chandelier and then screamed. A nearby pickup
truck was unaffected by these events.
The results should be printed to the screen.
Contents of input file:

Code:

with open("d1.txt", "r") as file:

text = file.read()

22
if "ADJECTIVE" in text:

adj = input("Enter Adjective: ")

text = text.replace("ADJECTIVE", adj)

if "NOUN" in text:

noun = input("Enter Noun: ")

text = text.replace("NOUN", noun)

if "ADVERB" in text:

adv = input("Enter Adverb: ")

text = text.replace("ADVERB", adv)

if "VERB" in text:

verb = input("Enter Verb: ")

text = text.replace("VERB", verb)

with open("d3.txt", "w") as file:

file.write(text)

print(text)

Output file:

23
Assignment-4
4.1 TechWorld, a technology training center, wants to allocate courses
for instructors.
An instructor is identified by name, technology skills, experience and average
feedback.
An instructor is allocated a course, if he/she satisfies the below two conditions:

● eligibility criteria:
● if experience is more than 3 years, average feedback should be 4.5
or more
● if experience is 3 years or less, average feedback should be 4
or more
● he/she should posses the technology skill for the course

Write a Python program to implement the class with its attributes and methods.
Note:

1. Consider all instance variables to be private and methods to be public


2. An instructor may have multiple technology skills, so consider
instance variable, technology_skill to be a list
3. check_eligibility(): Return true if eligibility criteria is satisfied by
the instructor. Else, return false
4. allocate_course(technology): Return true if the course which requires
the given technology can be allocated to the instructor. Else, return false
5. Perform case sensitive string comparison

Represent few objects of the class, initialize instance variables using setter
methods, invoke appropriate methods and test your program.

class TechWorld:

def init (self, name, skills, exp, feedback):

self._name = name

self._skills = skills

self._exp = exp

self._feedback = feedback

24
def check_eligibility(self):

if (self._exp>3 and self._feedback>=4.5) or (self._exp<=3 and self._feedback>=4):

print("Eligible, experience and feedback matches")

return True

else:

print("Not eligible, experience and feedback doesn't match")

return False

def allocate_course(self, tech):

if tech in self._skills:

print("Course skill present")

return True

else:

print("Skill not present")

return False

def final_decision(self,tech):

if (self.check_eligibility()==True) and (self.allocate_course(tech)==True):

print("Congratulations, allocation done!")

else:

print("Sorry, can't be allocated")

n = input("Enter name: ")

s = int(input("Enter number of skills: "))

skills = []

for i in range(s):

print("Enter skill ", i+1, ": ")

25
skill = input()

skills.append(skill)

e = float(input("Enter experience (in years): "))

f = float(input("Enter feedback rating (0 to 5): "))

appl = input("Enter technology for application: ")

obj = TechWorld(n, skills, e, f)

obj.final_decision("webdev")

Output:

4.2 Care hospital wants to calculate the bill amount to be paid by patients
visiting the hospital. Bill amount includes consultation fees and price of
medicines purchased from their pharmacy.

Write a Python program to implement the class diagram given below.

Method description:
calculate_bill_amount(consultation_fees, quantity_list, price_list): Accept
consultation_fees, quantity_list (quantities of medicines purchased) and
price_list (price per quantity of medicines purchased)

a. Calculate total bill amount to be paid by the patient. Bill amount


includes consultation fees and price of medicines
b. Initialize attribute, bill_amount with the total bill amount

26
Note: quantity_list and price_list have one-to-one correspondence. Quantity
and price per quantity of 1st medicine purchased by the patient is present at 0th
index of both lists, 2nd medicine is present at 1st index and so on.

For testing:

● Create objects of Bill class


● Invoke calculate_bill_amount(consultation_fees, quantity_list, price_list)
method on Bill object by passing consultation fees, quantity list and
price list
● Display bill id, patient name and bill amount

class Bill:

def init (self, bill_id, patient_name):

self.bill_id = bill_id

self.patient_name = patient_name

self.bill_amount = 0

def calculate_bill_amount(self, consultation_fees, quantity_list, price_list):

if len(quantity_list) != len(price_list):

print("Error: Quantity list and price list should have the same number of elements.")

return

medicines_cost = sum([quantity * price for quantity, price in zip(quantity_list, price_list)])

self.bill_amount = consultation_fees + medicines_cost

def display_bill(self):

print(f"Bill ID: {self.bill_id}")

print(f"Patient Name: {self.patient_name}")

print(f"Bill Amount: {self.bill_amount}")

# Testing the Bill class

bill1 = Bill(1, "gurwinder")

27
consultation_fees = 1000

quantity_list1 = [2, 3, 4] # Quantity of medicines

price_list1 = [50, 30, 20] # Price per quantity of medicines

bill1.calculate_bill_amount(consultation_fees, quantity_list1, price_list1)

bill1.display_bill()

Output:

4.3 An apparel shop wants to manage the items which it sells. Write a
python program to implement the class diagram given below.

Class Description:
Apparel class:

1. Initialize static variable counter to 100


2. In the constructor, auto-generate item_id starting from 101 prefixed by
"C" for cotton apparels and "S" for silk apparels. Example – C101, S102,
S103, C104 etc.
3. calculate_price(): Add 5% service tax on the price of the apparel
and update attribute, price with the new value

Cotton class:

1. While invoking parent constructor from child constructor, pass "Cotton"


as item_type
2. calculate_price(): Update attribute, price of Apparel class based on
rules given below
a. Add service tax on price by invoking appropriate method of
Apparel class
b. Apply discount on price
c. Add 5% VAT on final

price Silk class:

28
1. While invoking parent constructor from child constructor, pass "Silk"
as item_type
2. calculate_price(): Update attribute, price of Apparel class based on
rules given below
a. Add service tax on price by invoking appropriate method of
Apparel class
b. Identify points earned based on rules given below:

Silk apparels with price more than Rs. 10000, earn 10 points and
anything less than or equal to that earn 3 points

c. Initialize attribute, points with the identified points


d. Add 10% VAT on price

Note: Perform case sensitive string comparison

For testing:

● Create objects of Cotton class and Silk class


● Invoke calculate_price() on Cotton objects and Silk objects
● Display their details

class Apparel:

counter = 100

def init (self):

Apparel.counter += 1

self.item_id = ""

self.price = 0

def calculate_price(self):

self.price *= 1.05 # Add 5% service tax

class Cotton(Apparel):

def init (self):

super(). init ()

29
self.item_id = "C" + str(Apparel.counter)

self.item_type = "Cotton"

def calculate_price(self, discount):

super().calculate_price()

self.price -= discount

self.price *= 1.05 # Add 5% VAT

class Silk(Apparel):

def init (self):

super(). init ()

self.item_id = "S" + str(Apparel.counter)

self.item_type = "Silk"

self.points = 0

def calculate_price(self, discount):

super().calculate_price()

self.price *= 1.10 # Add 10% VAT

if self.price > 10000:

self.points = 10

else:

self.points = 3

# Create objects of Cotton class and Silk class

cotton_apparel = Cotton()

silk_apparel = Silk()

num_cotton_apparel = int(input("Enter the number of cotton apparels: "))

cotton_apparels = []

30
# Take input for cotton apparels

for _ in range(num_cotton_apparel):

cotton = Cotton()

cotton.price = float(input("Enter the price of the cotton apparel: "))

discount = float(input("Enter the discount for the cotton apparel: "))

cotton.calculate_price(discount)

cotton_apparels.append(cotton)

print("Cotton Apparel Details:")

for cotton in cotton_apparels:

print("Item ID:", cotton.item_id)

print("Item Type:",

cotton.item_type) print("Price:",

cotton.price)

print()

num_silk_apparel = int(input("Enter the number of silk apparels: "))

silk_apparels = []

# Take input for silk apparels

for _ in range(num_silk_apparel):

silk = Silk()

silk.price = float(input("Enter the price of the silk apparel: "))

discount = float(input("Enter the discount for the silk apparel: "))

silk.calculate_price(discount)

silk_apparels.append(silk)

print("Silk Apparel Details:")

for silk in silk_apparels:

31
print("Item ID:", silk.item_id)

print("Item Type:", silk.item_type)

print("Price:", silk.price)

print("Points Earned:", silk.points)

print()

Output:

4.4 Write a program to implement the concept of multiple inheritance.

a. Create the parent class Shape. Initialise the constructor with Shape.
b. Create another class named Rectangle which inherits the properties of the
parent class Shape. Define the attributes length and breadth in the
Rectangle class. Initialise the length and breadth inside the constructor of
the Rectangle class. Also call the constructor of the parent class to
initialise the color of the Rectangle. Define the method calc_area() to return
the area of the rectangle.
c. Create another class named Traingle which inherits the properties of the
parent class Shape. Define the attributes base and height on the Traingle
class. Initialize the base and height inside the constructor of the Traingle
class. Also call the constructor of the parent class to initialize the color of

32
the Traingle. Define the method calc_area() to return the area of the
Traingle.
d. Finally, create the instance of the Rectangle and Traingle classes to return
the area of the Rectangle and Traingle.

class Shape:

def colour(self, colour):

self.colour = colour

class Rectangle(Shape):

def init (self, l, b):

self.l = l

self.b = b

def calc_area(self):

return self.l * self.b, self.colour

class Triangle(Shape):

def init (self, b, h):

self.b = b

self.h = h

def calc_area(self):

return 0.5 * self.b * self.h, self.colour

l = int(input("Enter length of Rectangle: "))

b = int(input("Enter breadth of Rectangle: "))

Rect = Rectangle(l, b)

Rect.colour = input("Enter colour of Rectangle: ")

print(Rect.calc_area())

b = int(input("Enter base of Triangle: "))

33
h = int(input("Enter height of Triangle: "))

Tri = Triangle(b, h)

Tri.colour = input("Enter colour of Triangle: ")

print(Tri.calc_area())

Output:

34
Assignment-5
5.1 Assume that a poem is given. Write the regular expressions for the following:

1. Print how many times the letter 'v' appears in the poem.
2. Remove all the newlines from the poem and print the poem in a single line.
3. If a word has 'ch' or 'co', replace it with 'Ch' or 'Co'.
4. If the pattern has characters 'ai' or 'hi', replace the next three
characters with *\*.

Test your code by using the given sample inputs.


Sample Input:
If I can stop one heart from breaking,
I shall not live in vain;
If I can ease one life the aching,
Or cool one pain,
Or help one fainting robin
Unto his nest again,
I shall not live in vain.
Expected Output:
4

If I can stop one heart from breaking, I shall not live in vain; If I can ease one
life the aching, Or cool one pain, Or help one fainting robin Unto his nest
again, I shall not live in vain.

If I can stop one heart from breaking,


I shall not live in vain;
If I can ease one life the aChing,
Or Cool one pain,
Or help one fainting robin
Unto his nest again,
I shall not live in vain.

If I can stop one heart from breaking,


I shall not live in vain;
If I can ease one life the achi*\*
Or cool one pain,

35
Or help one fai*\*ng robin
Unto hi*\*est again,
I shall not live in vain.
import re

# Given poem
poem = '''If I can stop one heart from breaking,
I shall not live in vain;
If I can ease one life the aching,
Or cool one pain,
Or help one fainting robin
Unto his nest again,
I shall not live in vain.'''

count_v = len(re.findall(r'v', poem))


print(f"Number of times 'v' appears in the poem: {count_v}")

poem_single_line = re.sub(r'\n', ' ', poem)


print("\nPoem in a single line:")
print(poem_single_line)

modified_poem = re.sub(r'ch', 'Ch', poem)


modified_poem = re.sub(r'co', 'Co', modified_poem)
print("\nPoem with 'ch' or 'co' replaced with 'Ch' or 'Co':")
print(modified_poem,end="\n\n")

poem_modified = re.sub(r'ai.{3}', 'ai*\*', poem)


poem_modified = re.sub(r'hi.{3}', 'hi*\*', poem_modified)
print(poem_modified)
Output:

36
5.2 Write a python program to validate the details provided by a user as part
of registering to a web application.

Write a function validate_name(name) to validate the user name. Name should


not be empty, name should not exceed 15 characters. Name should contain only
alphabets
Write a function validate_phone_no(phoneno) to validate the phone number.
Phone number should have 10 digits, Phone number should not have any
characters or special characters, All the digits of the phone number should not be
same.
Example: 9999999999 is not a valid phone number

Write a function validate_email_id(email_id) to validate email Id.It should contain


one '@' character and '.com', '.com' should be present at the end of the email id.
Domain name should be either 'gmail', 'yahoo' or 'hotmail'
Note: Consider the format of email id to be username@domain_name.com
All the functions should return true if the corresponding value is valid.
Otherwise, it should return false.
import re

def validate_name(name):
# Validate the user
name
if not re.match(r'^[a-zA-Z]{1,15}$', name):
return False
return True

def validate_phone_no(phoneno):
# Validate the phone number

37
if not re.match(r'^\d{10}$', phoneno):
return False
if len(set(phoneno)) == 1:
return False
return True

def validate_email_id(email_id):
# Validate the email ID
email_pattern = r'^[a-zA-Z0-9._%+-]+@(gmail|yahoo|hotmail)\.com$'
if re.match(email_pattern, email_id):
return True
return False

# Testing the functions


def main():
name = input("Enter your name: ")
phoneno = input("Enter your phone number: ")
email_id = input("Enter your email ID: ")

print(f"Is name '{name}' valid?\n {validate_name(name)}")


print(f"Is phone number '{phoneno}' valid?\n {validate_phone_no(phoneno)}")
print(f"Is email ID '{email_id}' valid?\n {validate_email_id(email_id)}")

if name == " main ":


main()

Output:

38
5.3 Write a python program that accepts a text and displays a string which
contains the word with the largest frequency in the text and the frequency
itself separated by a space.

Rules:

1. The word should have the largest frequency.


2. In case multiple words have the same frequency, then choose the word
that has the maximum length.

Assumptions:

1. The text has no special characters other than space.


2. The text would begin with a word and there will be only a single
space between the words.

Perform case insensitive string comparisons wherever necessary.


Sample Input1:
"Work like you do not need money love like you have never been hurt and dance
like no one is watching"
Expected Output: like 3
Sample Input2:
"Courage is not the absence of fear but rather the judgement that something else
is more important than fear"
Expected Output: fear 2

import re

def most_frequent_word(text):

text = text.lower()

words = re.split(r'\s+', text)

freq = {}

for word in words:

if word in freq:

freq[word] += 1

39
else:

freq[word] = 1

max_freq = 0

max_word = ''

for word, frequency in freq.items():

if frequency > max_freq:

max_freq = frequency

max_word = word

elif frequency == max_freq and len(word) > len(max_word):

max_word = word

return max_word + ' ' + str(max_freq)

print(most_frequent_word("Work like you do not need money love like you have never been hurt
and dance like no one is watching"))

print(most_frequent_word("Courage is not the absence of fear but rather the judgement that
something else is more important than fear"))

Output:

5.4 type(). The type() built-in function returns a type object which is displayed
as a Pythonic-looking string:
>>> type(0)
<type 'int'>
>>> type(.34)
<type 'float'>
>>> type(dir)
<type 'builtin_function_or_method'>
Create a RE that would extract out the actual type name from the string. Your
function should take a string like this " <type 'int'>" and return 'int'. (Ditto for all
other types, i.e., 'float', 'builtin_function_or_method', etc.)

40
import re

def extract_type_name(type_string):

match = re.search(r"<type '(.*)'>", type_string)

if match:

return match.group(1)

return None # Return None if no match is found

type_string = "<type 'int'>"

type_name = extract_type_name(type_string)

print(type_name)

Output:

41
Assignment - 6
6.1 You are provided with the below code. Add a try/except clause so the code
runs without errors. If a blog post didn’t get any likes, a ‘Likes’ key should be
added to that dictionary with a value of 0.
blog_posts = [{'Photos': 3, 'Likes': 21, 'Comments': 2}, {'Likes': 13, 'Comments': 2,
'Shares': 1}, {'Photos': 5, 'Likes': 33, 'Comments': 8, 'Shares': 3}, {'Comments': 4,
'Shares': 2}, {'Photos': 8, 'Comments': 1, 'Shares': 1}, {'Photos': 3, 'Likes': 19,
'Comments': 3}]
total_likes = 0
for post in blog_posts:
total_likes = total_likes + post['Likes']
Hint: Run the above code to see the error message. The message indicates that
you are trying to access an element of a dictionary, but the dictionary does not
have that key you are using. You may have a typo in the name of your key. It is
also good practice to check if the key exists using a statement like if key in
mydict. You can also use mydict.get(key,defaultvalue) so that if the key is not in
the dictionary you get the default value instead of an error.

blog_posts = [{'Photos': 3, 'Likes': 21, 'Comments': 2}, {'Likes': 13, 'Comments': 2, 'Shares': 1},

{'Photos': 5, 'Likes': 33, 'Comments': 8, 'Shares': 3}, {'Comments': 4, 'Shares': 2},

{'Photos': 8, 'Comments': 1, 'Shares': 1}, {'Photos': 3, 'Likes': 19, 'Comments': 3}]

total_likes=0

for post in blog_posts:

try:

total_likes = total_likes + post['Likes']

except KeyError:

total_likes = total_likes + 0

print(total_likes)

42
Output:

6.2 The code below assigns the 5th letter of each word in food to the new list fifth.
However, the code currently produces errors. Insert a try/except clause that will
allow the code to run and produce a list of the 5th letter in each word. If the word
is not long enough, it should not print anything out. Note: The pass statement is
a null operation; nothing will happen when it executes.

food = ["chocolate", "chicken", "corn", "sandwich", "soup", "potatoes", "beef",


"lox", "lemonade"]
fifth = []
for x in food:
fifth.append(x[4])
Hint: Run the above code to see the error message. The message means that you
are trying to index past the end of a string or a list. For example if your list has 3
things in it and you try to access the item at position 3 or more. Remember that
the first item in a list or string is at index position 0, quite often this message
comes about because you are off by one. Remember in a list of length 3 the last
legal index is 2

food = ["chocolate", "chicken", "corn", "sandwich", "soup", "potatoes", "beef", "lox", "lemonade"]

fifth = []

for x in food:

try:

fifth.append(x[4])

except IndexError:

pass

print(fifth)

Output:

43
6.3 Install SQLite/MySql and verify its installation by creating a test database.

import sqlite3

sqliteConnection = sqlite3.connect('test.db')

cursor = sqliteConnection.cursor()

print('init db')

query = 'select sqlite_version();'

cursor.execute(query)

result = cursor.fetchall()

print('SQLite Version is {}'.format(result))

Output:

6.4 Create a table Employee in test with the following


Fields: First_Name CHAR(20) NOT NULL
Last_Name CHAR(20)
Age INT
Gender CHAR(1)
Department CHAR(20)
Income FLOAT
Insert values into the Employee table by adding multiple records. Also, access
the Employee table data and print all its data.

import sqlite3

sqliteConnection = sqlite3.connect('test1.db')

44
cursor = sqliteConnection.cursor()

cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

table="""CREATE TABLE EMPLOYEE

(First_Name CHAR(20) NOT NULL,

Last_Name CHAR(20),

Age INT,

Gender CHAR(1),

Department CHAR(20),

Income FLOAT);"""

cursor.execute(table)

cursor.execute('''INSERT INTO EMPLOYEE VALUES ('Raju','Shrivastav',


27,'M','Technical',12000.0)''')

cursor.execute('''INSERT INTO EMPLOYEE VALUES ('Jobanpreet','Singh',


27,'M','Training',12000.0)''')

cursor.execute('''INSERT INTO EMPLOYEE VALUES ('gaurav','kumar',


27,'M','Advertising',12000.0)''')

cursor.execute('''INSERT INTO EMPLOYEE VALUES ('Shyam','Sundar',


28,'M','Technical',20000.0)''')

cursor.execute('''INSERT INTO EMPLOYEE VALUES ('Baburao','Bhaskar',


49,'M','Management',15000.0)''')

data=cursor.execute('''SELECT * FROM EMPLOYEE''')

for row in data:

print(row)

Output:

45
46
47

You might also like