Jobanpy
Jobanpy
Jobanpy
n=4
for i in range(1,
n+1): for j in
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.
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.
AAAABBBBCCCCCCCC 4A4B8C
AABCCA 2A1B2C1A
def run_length_encode(s):
if not s:
return ""
encoded = ""
count = 1
count += 1
else:
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)
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:
class StudentMarks:
self.marks = marks
def find_more_than_average(self):
total_marks = sum(self.marks)
return percentage_above_average
def generate_frequency(self):
frequency = [0] * 26
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()
frequency = student_data.generate_frequency()
print("Frequency of marks:")
l=[*range(1,26)]
print(l)
print(frequency)
sorted_marks = student_data.sort_marks()
Output:
def odd():
def even():
def sum_of_numbers(func=None):
if func is None:
return sum(sample_data)
else:
numbers = func()
return sum(numbers)
# Example usage:
even_sum = sum_of_numbers(even)
odd_sum = sum_of_numbers(odd)
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.
backward,drawback False
(Reason: character
'a' repeats at position
6, not an anagram)
Reductions,discounter True
def check_anagram(str1,str2):
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:
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.
def digit_sum(n):
return -1
if not valid_numbers:
return -1
return max(valid_numbers)
10
# Example usage:
num1 = 10
num2 = 99
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
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 = {
return result
# Example usage:
12
given_tuple = (5, 3.14, 'apple', True, 'banana', 7, False, 2.718, 'cherry', 10)
result = categorize_elements(given_tuple)
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+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:
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
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)
find_correct(D)
Output:
16
Assignment-3
3.1 Write a python program to compute the area of circle, square, and rectangle
using module.
import math
def circle_area(radius):
def square_area(side):
return side ** 2
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)
# Square
17
side_length = 7
square_area = shapes.square_area(side_length)
# Rectangle
length = 4
width = 6
print(f"Area of the rectangle with length {length} and width {width} is: {rectangle_area}")
Output:
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.
Code:
content = file.read()
length = len(content)
if length % 2 != 0:
else:
half1 = content[:length // 2]
file.write(swapped_content)
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:
lines = file.readlines()
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:
text = file.read()
22
if "ADJECTIVE" in text:
if "NOUN" in text:
if "ADVERB" in text:
if "VERB" in text:
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:
Represent few objects of the class, initialize instance variables using setter
methods, invoke appropriate methods and test your program.
class TechWorld:
self._name = name
self._skills = skills
self._exp = exp
self._feedback = feedback
24
def check_eligibility(self):
return True
else:
return False
if tech in self._skills:
return True
else:
return False
def final_decision(self,tech):
else:
skills = []
for i in range(s):
25
skill = input()
skills.append(skill)
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.
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)
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:
class Bill:
self.bill_id = bill_id
self.patient_name = patient_name
self.bill_amount = 0
if len(quantity_list) != len(price_list):
print("Error: Quantity list and price list should have the same number of elements.")
return
def display_bill(self):
27
consultation_fees = 1000
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:
Cotton 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
For testing:
class Apparel:
counter = 100
Apparel.counter += 1
self.item_id = ""
self.price = 0
def calculate_price(self):
class Cotton(Apparel):
super(). init ()
29
self.item_id = "C" + str(Apparel.counter)
self.item_type = "Cotton"
super().calculate_price()
self.price -= discount
class Silk(Apparel):
super(). init ()
self.item_type = "Silk"
self.points = 0
super().calculate_price()
self.points = 10
else:
self.points = 3
cotton_apparel = Cotton()
silk_apparel = Silk()
cotton_apparels = []
30
# Take input for cotton apparels
for _ in range(num_cotton_apparel):
cotton = Cotton()
cotton.calculate_price(discount)
cotton_apparels.append(cotton)
print("Item Type:",
cotton.item_type) print("Price:",
cotton.price)
print()
silk_apparels = []
for _ in range(num_silk_apparel):
silk = Silk()
silk.calculate_price(discount)
silk_apparels.append(silk)
31
print("Item ID:", silk.item_id)
print("Price:", silk.price)
print()
Output:
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:
self.colour = colour
class Rectangle(Shape):
self.l = l
self.b = b
def calc_area(self):
class Triangle(Shape):
self.b = b
self.h = h
def calc_area(self):
Rect = Rectangle(l, b)
print(Rect.calc_area())
33
h = int(input("Enter height of Triangle: "))
Tri = Triangle(b, h)
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 *\*.
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.
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.'''
36
5.2 Write a python program to validate the details provided by a user as part
of registering to a web application.
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
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:
Assumptions:
import re
def most_frequent_word(text):
text = text.lower()
freq = {}
if word in freq:
freq[word] += 1
39
else:
freq[word] = 1
max_freq = 0
max_word = ''
max_freq = frequency
max_word = word
max_word = word
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):
if match:
return match.group(1)
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},
total_likes=0
try:
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:
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')
cursor.execute(query)
result = cursor.fetchall()
Output:
import sqlite3
sqliteConnection = sqlite3.connect('test1.db')
44
cursor = sqliteConnection.cursor()
Last_Name CHAR(20),
Age INT,
Gender CHAR(1),
Department CHAR(20),
Income FLOAT);"""
cursor.execute(table)
print(row)
Output:
45
46
47