Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Codekata Report 1716960172939

Download as pdf or txt
Download as pdf or txt
You are on page 1of 177

Codekata Report:

Name: AKSHAT RAJ

Email: akshatraj873@gmail.com

Specialization: School of Computing Science & Engineering

Completion Year: 2027

Section: Section-10

1. Write a code to get the input in the given format and print the
output in the given format

)
m
Sample Input: .co
ail
gm

2
@
738

Sample Output:
raj
at

2
h
ks
(a

Completion Status: Not Completed


AJ
TR
HA

Concepts Included:
S
AK

Input/Output

Language Used: PYTHON 3

Source Code:
#A Simple Hello World
print("Hello World")

#Getting input via STDIN


a= into(input('enter the number'))
print("The Input Provided is: ",a+ 5)

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Hello World

Compilation Status: Failed


Execution Time:
0.01s

TestCase2:
Input:

)
m
.co
< hidden >
ail
Expected Output:
gm
@

< hidden >


738

Output:
raj
hat

Hello World
ks
(a

Compilation Status: Failed


AJ
TR

Execution Time:
HA

0.009s
S
AK

2. You are required to write a program that calculates and prints the
perimeter of a triangle given its three sides a, b, and c units.
Implement a class named 'Triangle' without any parameter in its
constructor.

Input:
The input consists of three lines. Each line contains an integer representing one side
of the triangle.

Output:
Output the perimeter of the triangle.

Sample Input:
345

Sample Output:
12

Input Description:
side1
side2
side3

Output Description:
perimeter

Completion Status: Completed

)
m
.co
Concepts Included: ail
GU-INTRODUCTION TO OOP
gm
@
73

Language Used: PYTHON 3


8
raj
at

Source Code:
h
ks
(a

class Triangle:
AJ

def __init__(self):
TR

self.a=int(input())
HA

self.b=int(input())
self.c=int(input())
S
AK

def peri(self):
peri=self.a+self.b+self.c
print(peri)

tri=Triangle()
tri.peri()

Compilation Details:

TestCase1:
Input:
< hidden >
Expected Output:
< hidden >

Output:
12

Compilation Status: Passed


Execution Time:
0.009s

TestCase2:
Input:
< hidden >

Expected Output:

)
m
.co
< hidden >
ail
Output:
gm
@

9
738

Compilation Status: Passed


raj
h at

Execution Time:
ks
(a

0.014s
AJ
TR
HA

3. You are required to write a program that calculates and prints the
S
AK

area of a triangle given its base and height. Implement a class


named 'Triangle' without any parameter in its constructor.

Input:
The input consists of two lines. Each line contains an integer representing either the
base or the height of the triangle.

Output:
Output the area of the triangle.

Sample Input:
66

Sample Output:
18

Input Description:
Base
Height

Output Description:
Area

Completion Status: Completed

Concepts Included:
GU-INTRODUCTION TO OOP

)
Language Used: PYTHON 3

m
.co
ail
Source Code:
gm
@

class Triangle:
73

def __init__(self):
8
raj

self.base = int(input())
at

self.height = int(input())
h
ks

def area(self):
(a

area = 0.5 * self.base * self.height


AJ

print(area)
TR
HA

tri = Triangle()
S
AK

tri.area()

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
18.0

Compilation Status: Passed


Execution Time:
0.01s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
32.0

Compilation Status: Passed


Execution Time:

)
m
.co
0.01s
ail
gm
@

4. You're required to write a program to calculate and print the area


73

and perimeter of two rectangles given their sides. Implement a


8
raj

class named 'Rectangle' with methods named 'Area' and 'Perimeter',


at

which return the area and perimeter, respectively. The length and
h
ks

breadth of the rectangles are passed as parameters to its


(a

constructor.
AJ
TR
HA

Input:
S
AK

The input consists of two lines. Each line contains two integers representing the
sides of the rectangles in the format (a, b) for the first rectangle and (c, d) for the
second rectangle.

Output:
Output the area and perimeter of both rectangles separated by spaces in the
formatArea1 Perimeter1Area2 Perimeter2.

Sample Input:
3 44 5

Sample Output:
12 1420 18
Input Description:
Get input sides of the two rectangles.
Rectangle 1 = (a , b)
Rectangle 1 = (c , d)

Output Description:
Area1 Perimeter1
Area2 Perimeter2

Completion Status: Completed

Concepts Included:
GU-INTRODUCTION TO OOP

Language Used: PYTHON 3

)
m
.co
Source Code: ail
gm

class Rectangle:
@

def __init__(self,leng,brea):
73

self.length = leng
8

self.breadth = brea
raj
h at
ks
(a

def Area(self):
AJ

peri = 2*(self.length+self.breadth)
TR

area = self.length * self.breadth


S HA

print (area,peri)
AK

a,b = map(int,input().split())
c,d = map(int,input().split())

rec1 = Rectangle(a,b)
rec2 = Rectangle(c,d)

rec1.Area()
rec2.Area()

Compilation Details:

TestCase1:
Input:
< hidden >
Expected Output:
< hidden >

Output:
12 14
20 18

Compilation Status: Passed


Execution Time:
0.009s

TestCase2:
Input:
< hidden >

)
m
Expected Output:
.co
< hidden >
ail
gm

Output:
@
73

20 18
8
raj

25 20
hat

Compilation Status: Passed


ks
(a

Execution Time:
AJ
TR

0.01s
HA
S
AK

5. You are tasked with writing a program to calculate and print the
area and circumference of a circle given its radius r units.
Implement a class named 'Circle' without any parameter in its
constructor.

Input:
The input consists of a single line containing an integer r representing the radius of
the circle.

Output:
Output the area and circumference of the circle. Round the output to one decimal
value.

Sample Input:
3

Sample Output:
28.318.8

Input Description:
r

Output Description:
Area
Circumference
Note: Round the output to one decimal values

Completion Status: Completed

)
m
.co
Concepts Included: ail
GU-INTRODUCTION TO OOP
gm
@
73

Language Used: PYTHON 3


8
raj
at

Source Code:
h
ks
(a

import math
AJ
TR

class Circle:
HA

def area(self, r):


S
AK

return round(math.pi *r**2,1)

def circumference(self, r):


return round(2*math.pi*r,1)

def main():
circle = Circle()

r= int(input())

print(circle.area(r))
print(circle.circumference(r))

if __name__ == "__main__":
main()

Compilation Details:
TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
28.3
18.8

Compilation Status: Passed


Execution Time:
0.01s

)
m
TestCase2:
.co
ail
Input:
gm

< hidden >


@
73

Expected Output:
8
raj
at

< hidden >


h
ks

Output:
(a
AJ

50.3
TR

25.1
HA

Compilation Status: Passed


S
AK

Execution Time:
0.01s

6. Write a code to get the input in the given format and print the
output in the given format

Sample Input:
2345678

Sample Output:
2345678

Completion Status: Not Completed


Concepts Included:
Input/Output

Language Used: PYTHON 3

Source Code:
#A Simple Hello World
print("Hello World")

#Getting input via STDIN


userInput = input()
print(userInput,"_")

Compilation Details:

TestCase1:

)
m
.co
Input: ail
< hidden >
gm
@

Expected Output:
738
raj

< hidden >


h at

Output:
ks
(a

Hello World
AJ

2345678_
TR
HA

Compilation Status: Failed


S
AK

Execution Time:
0.009s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Hello World
12 13 14 15 16 17 18 _

Compilation Status: Failed


Execution Time:
0.009s

7. Write a program to print the first “n” Fibonacci series numbers,


where n is a positive integer. If the input is zero and print the output
“ZeRo”

Sample Input:
2

Sample Output:
11

Completion Status: Not Completed

)
m
Concepts Included: .co
ail
gm

galgotias - basics
@
73

galgotias
8
raj
at

Language Used: PYTHON 3


h
ks
(a

Source Code:
AJ
TR

def fibonacci(n):
HA

if n == 0:
S

return "ZeRo"
AK

elif n == 1:
return [1]
elif n == 2:
return [1, 1]
else:
fib_series = [1, 1]
for i in range(2, n):
fib_series.append(fib_series[i-1] + fib_series[i-2])
return fib_series

n = int(input())
print(fibonacci(n))

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
[1, 1]

Compilation Status: Failed


Execution Time:
0.012s

TestCase2:
Input:
< hidden >

)
m
.co
Expected Output:
ail
< hidden >
gm
@

Output:
738

[1, 1, 2, 3, 5, 8]
raj
at

Compilation Status: Failed


h
ks
(a

Execution Time:
AJ
TR

0.012s
HA
S
AK

8. Write a program to find the area of a rectangle. If the input or


output value is floating point roundoff to nearest integer.

Sample Input:
24

Sample Output:
8

Completion Status: Not Completed

Concepts Included:
galgotias - basics
galgotias

Language Used: PYTHON 3

Source Code:
length = round(float(input()))
width = round(float(input()))

area = length * width

print(area)

Compilation Details:

TestCase1:
Input:

)
m
.co
< hidden >
ail
Expected Output:
gm
@

< hidden >


73
8

Output:
raj
hat

Traceback (most recent call last):


ks

File "script-3.8.1.py", line 1, in <module>


(a

length = round(float(input()))
AJ

ValueError: could not convert string to float: '2 4'


TR
HA
S

Runtime Error (NZEC)


AK

Compilation Status: Failed


Execution Time:
0.01s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Traceback (most recent call last):
File "script-3.8.1.py", line 1, in <module>
length = round(float(input()))
ValueError: could not convert string to float: '89 6'

Runtime Error (NZEC)

Compilation Status: Failed


Execution Time:
0.01s

9. Vishakan, a dedicated reader, has a limited time to indulge in his


favorite activity: reading books in the library. Each book has its own
unique charm, but Vishakan needs to optimize his time to read as
many books as possible within his available time.

)
m
Input:
.co
ail
gm

The first line contains two integers,(n) and (t) where, (1 <= n <= 10^5) and (1 <= t <=
10^9), denoting the number of books in the library and the total free minutes Vishakan
@
73

has.
8
raj

The second line contains( n) space-separated integers (a1, a2,...., an) where (1 <= ai
at

<= 10^4), representing the time required to read each book.


h
ks
(a
AJ

Output:
TR
HA

Print a single integer, the maximum number of books Vishakan can read within his
S

available time.
AK

Constraints:

Vishakan has a maximum of( 10^9) minutes to spend in the library.

Each book takes between 1 and 10,000 minutes to read.

Sample input:

3 32 2 3

Sample output:

Completion Status: Completed


Concepts Included:
gu - introduction to oops: unit 1

Language Used: PYTHON 3

Source Code:
import sys
from collections import deque, defaultdict

I = sys.stdin.readline

def ii():
return int(I().strip())

def li():
return list(map(int, I().strip().split()))

)
m
def mi():

.co
return map(int, I().strip().split()) ail
gm

def main():
n, k = mi()
@
73

arr = li()
8
raj

#..... YOUR CODE STARTS HERE .....


h at
ks

maxlen = 0
(a

s=sum(arr)
AJ

if s <= k:
TR

print(n)
HA

else:
S

curr=0
AK

j=0
for i in range(n):
curr+=arr[i]
while curr > k:
curr -=arr[i]
j+=arr[j]

maxlen=max(maxlen,i-j+1)
print (maxlen)

#..... YOUR CODE ENDS HERE .....

if __name__ == '__main__':
main()

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
1

Compilation Status: Passed


Execution Time:
0.015s

TestCase2:
Input:

)
m
.co
< hidden >
ail
Expected Output:
gm
@

< hidden >


738

Output:
raj
hat

0
ks
(a

Compilation Status: Passed


AJ
TR

Execution Time:
HA

0.012s
S
AK

10. Mani finds himself in a queue of( n) people but is uncertain


about his exact position. However, he's confident that there are at
least( a) people in front of him and at most( b) people behind him.
Mani seeks to determine the number of different positions he could
occupy in the queue.
Input:

The input consists of a single line containing three integers:( n),( a), and( b)
(( 0≤a,b<n≤100)). These represent the total number of people in the queue, the
minimum number of people in front of Mani, and the maximum number of people
behind Mani, respectively.

Output:
Print a single integer, the number of possible positions Mani could occupy in the
queue.

Constraints:

The queue contains between 1 and 100 people.

Mani is certain there are at least 0 people in front of him and at most( n-1) people
behind him.

Sample input:

523

Sample output:

Completion Status: Completed

)
m
.co
ail
Concepts Included:
gm

gu - introduction to oops: unit 1


@
738
raj

Language Used: PYTHON 3


h at
ks

Source Code:
(a
AJ

n,a,b = map(int, input().split())


TR
HA

#..... YOUR CODE STARTS HERE .....


S
AK

if(a+b==n):
print(b)
else:
print(b+1)

#..... YOUR CODE ENDS HERE .....

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >
Output:
3

Compilation Status: Passed


Execution Time:
0.009s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:

)
m
.co
1
ail
Compilation Status: Passed
gm
@

Execution Time:
738
raj

0.009s
at
h
ks
(a

11. Lucas, a university student, is working on a project where he


AJ

needs to process a set of student records. He is given a list of


TR

students where each record contains the student's name and marks
HA

in three subjects: Math, Physics, Biology. Each subject's mark is


S
AK

within the range 0-100. He needs to return the name of the student
with the highest average score.
If there is more than one student who has the highest average score, Lucas needs to
return the first student in the list.

Input:

The first line contains an integer 'n' (1 <= n <= 1000) - representing the number of
students.

The 'n' following lines each contain a string and three space-separated integers.

Output:

Print the name of the student who has the highest average score.
Sample Input:
5

John 85 90 82

Alice 90 91 92

Bob 80 79 81

Lucas 88 90 92

Maria 90 91 90

Sample Output:
Alice

Note:

)
The five students' average scores are as follows:

m
.co
ail
John's average is 85.67
gm

Alice's average is 91
@
73

Bob's average is 80
8
raj
at

Lucas's average is 90
h
ks

Maria's average is 90.33


(a
AJ
TR

Alice has the highest average score and showcases the best performance among all
students.
HA
S
AK

Completion Status: Completed

Concepts Included:
gu - introduction to oops: unit 1

Language Used: PYTHON 3

Source Code:
class Student:
def __init__(self, name, scores):
self._name = name # protected attribute
self.__scores = scores # private attribute

def calculate_average(self):
return sum(self.__scores) / len(self.__scores)
def get_name(self): # public method to access protected attribute
return self._name

class TopStudentFinder:
def __init__(self):
self.max_avg = -1.0
self.top_student = ""

def find_top_student(self, students):


#..... YOUR CODE STARTS HERE .....

for student in students:


avg_marks=student.calculate_average()
if avg_marks>self.max_avg:
self.max_avg=avg_marks
self.top_student=student.get_name()

#..... YOUR CODE ENDS HERE .....

)
m
def get_top_student(self):

.co
return self.top_student ail
gm
@

if __name__ == "__main__":
73

n = int(input())
8

students_data = []
raj
h at

for _ in range(n):
ks

student_info = input().split()
(a

name = student_info[0]
AJ

scores = list(map(int, student_info[1:]))


TR

students_data.append(Student(name, scores))
HA
S

#..... YOUR CODE STARTS HERE .....


AK

top_student=TopStudentFinder()
top_student.find_top_student(students_data)
print(top_student.get_top_student())

#..... YOUR CODE ENDS HERE .....

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >
Output:
Alice

Compilation Status: Passed


Execution Time:
0.01s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:

)
m
.co
John
ail
Compilation Status: Passed
gm
@

Execution Time:
738
raj

0.01s
at
h
ks
(a

12. Many years ago, the country of Berland was inhabited by a small
AJ

population of( n) individuals, each with their own savings. The


TR

government aimed to increase the number of wealthy individuals by


HA

implementing a series of reforms.


S
AK

Each reform involved the government selecting a subset of individuals, collecting all
their savings, and then redistributing the total equally among the selected individuals.
The ultimate goal was to ensure that each individual had at least( x) burles to be
considered wealthy.

Given the initial savings of each individual and the minimum wealth threshold( x),
your task is to calculate the maximum possible number of wealthy individuals after
the reforms, if any were implemented.

Input:

The first line contains a single integer( T) where, ( 1 <= T <= 1000) — the number of
test cases.

For each test case, there are two lines:

- The second line contains two integers( n) and( x) where, (1 <= n <= 10^5, 1 <= x <=
10^9) — representing the number of individuals and the minimum wealth threshold.

- The third line contains( n) integers( a1, a2,...., an) where, ( 1 <= ai <= 10^9) — the
initial savings of each individual.

Output:

Print( T) integers, one per test case, representing the maximum possible number of
wealthy individuals after the reforms.

Constraints:

The total sum of( n) across all test cases does not exceed( 10^5).

Sample input:

1 1 2 13

Sample output:

)
m
Completion Status: Completed .co
ail
gm
@

Concepts Included:
738

gu - introduction to oops: unit 1


raj
h at
ks

Language Used: PYTHON 3


(a
AJ

Source Code:
TR
HA

class TestCase:
S

def __init__(self, n, x, a):


AK

self.n = n
self.x = x
self.a = a

def calculate_qualified_elements(self):
a_sorted = sorted(self.a, reverse=True)
p, q = 0, 0
#..... YOUR CODE STARTS HERE .....

for i in range(self.n):
p+=a_sorted[i]
if p<(i+1)*self.x:
break
q+=1

#..... YOUR CODE ENDS HERE .....


return q
def process_test_cases():
test_cases = int(input())
results = []

for _ in range(test_cases):
n, x = map(int, input().split())
a = list(map(int, input().split()))
#..... YOUR CODE STARTS HERE .....

case=TestCase(n,x,a)
results.append(case.calculate_qualified_elements())

#..... YOUR CODE ENDS HERE .....

return results

if __name__ == "__main__":
results = process_test_cases()

)
m
for result in results:

.co
print(result) ail
gm

Compilation Details:
@
738

TestCase1:
raj
h at

Input:
ks
(a

< hidden >


AJ
TR

Expected Output:
HA

< hidden >


S
AK

Output:
1

Compilation Status: Passed


Execution Time:
0.016s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >
Output:
2
4
0
3

Compilation Status: Passed


Execution Time:
0.01s

13. On Earth, each plane has a special affinity for another plane.
Given a group of n planes, numbered from 1 to n, where plane i likes
plane fi, we aim to determine if any love triangle exists.

Input:

)
m
.co
The first line contains a single integer n (2 ≤ n ≤ 5000) — representing the number of
planes. ail
gm

The second line contains n integers f1, f2, ..., fn (1 ≤ fi ≤ n, fi ≠ i), indicating that the i-th
@

plane is fond of plane fi.


73
8
raj

Output:
at
h
ks

Output "YES" if there exists a love triangle among the planes. Otherwise, output "NO".
(a
AJ

Sample input:
TR

55 5 5 5 1
SHA

Sample output:
AK

NO

Completion Status: Completed

Concepts Included:
gu - introduction to oops: unit 1

Language Used: PYTHON 3

Source Code:
class CycleChecker:
def __init__(self, f):
self.f = f
self.n = len(f)
def check_cycle(self):
#..... YOUR CODE STARTS HERE .....

for i in range(self.n):
if self.f[self.f[self.f[i]-1]-1]==i+1:
return "YES"
else:
return "NO"

#..... YOUR CODE ENDS HERE .....

if __name__ == "__main__":
n = int(input())
f = list(map(int, input().split()))

#..... YOUR CODE STARTS HERE .....

ob=CycleChecker(f)
print(ob.check_cycle())

)
m
#..... YOUR CODE ENDS HERE .....

.co
ail
Compilation Details:
gm
@
73

TestCase1:
8
raj

Input:
h at
ks

< hidden >


(a
AJ

Expected Output:
TR

< hidden >


HA
S

Output:
AK

NO

Compilation Status: Passed


Execution Time:
0.01s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
YES

Compilation Status: Passed


Execution Time:
0.01s

14. Richard Hendricks, Gilfoyle, and Dinesh, the brilliant minds


behind Pied Piper, are on a mission to optimize their messaging
platform's data compression algorithm. They aim to represent "Yes"
and "No" messages more efficiently by converting them into a
different base that requires fewer characters, thus reducing the
overall message size.
Richard explains that they currently represent "Yes" messages as 1 and "No"
messages as 0 in their messaging platform. However, he believes they can further
compress this representation by changing the base to a more efficient one, achieving

)
m
a four-fold decrease in the number of characters needed to represent the messages.

.co
Gilfoyle immediately jumps in, suggesting a strategy to change the base of the
ail
representation to achieve their goal. With his expertise in cryptography and data
gm

compression, Gilfoyle proposes a solution to map the binary representation onto a


@

different base that requires only one-fourth of the characters needed in the existing
73

base.
8
raj
at

Help Gilfoyle defend his case and determine the optimal base for representing "Yes"
h

and "No" messages to achieve a four-fold decrease in the number of characters


ks
(a

required.
AJ
TR

Input:
SHA
AK

A single line containing a string made up of 0's and 1's representing "Yes" and "No"
messages.

Input Constraints: 1 ≤ N ≤ 57, where N is the number of characters (0's and 1's) in the
string.

Output:
Single line denoting the value of the binary string in a base that uses four times fewer
characters than the existing base.

Sample input:

10110111000010010011011001010111111000111010010010000

Sample output:

16e126cafc7490
Completion Status: Completed

Concepts Included:
gu - introduction to oops: unit 1

Language Used: PYTHON 3

Source Code:
a = input()

#..... YOUR CODE STARTS HERE .....

s=""
a=int(a)
while a>0:
d=a%10000
j=0

)
m
c=0
.co
ail
while d>0:
gm

b=d%10
@

c+=b*(2**j)
73

j+=1
8
raj

d//=10
h at
ks

if(c==10):
(a

s+='a'
AJ

elif(c==11):
TR

s+='b'
elif(c==12):
HA

s+='c'
S
AK

elif(c==13):
s+='d'
elif(c==14):
s+='e'
elif(c==15):
s+='f'
else:
s+=str(c)
a//=10000
w=""
for i in range(len(s)-1,-1,-1):
w+=s[i]
print(w)

#..... YOUR CODE ENDS HERE .....

Compilation Details:
TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
16e126cafc7490

Compilation Status: Passed


Execution Time:
0.01s

TestCase2:

)
m
.co
Input: ail
gm

< hidden >


@

Expected Output:
738
raj

< hidden >


hat

Output:
ks
(a

b7093657e3a4
AJ
TR

Compilation Status: Passed


HA

Execution Time:
S
AK

0.009s

15. Sanjay is a Stock Exchange Specialist. Any stocks that he buys,


he has a capacity of for such greater price. He has created a
algorithm to find the profit that can be obtained by trading certain
stocks.
The machines will be generating a string, the string will be made up of integers from 0
to 9. Now each integer in this string will be a coded value of the profit. You have to
multiply a digit N, with n-1,n-2,...till n-i>=1. Each digit in the string will be giving a profit
of the particular amount thus obtained. Now summing up all the profits, it should be
equal to the entire string considered as a integer input.

If they are equal, then the prediction was right, so print Right, if else print Wrong.

Input:
One single string input N, where N is the prediction by Victor

Input Constraints : 1<=length of N<=10^5

Output:
"Right" if the prediction is right and "Wrong" if the prediction is wrong

Sample input:

40583

Sample output:

Wrong

Completion Status: Completed

Concepts Included:

)
m
gu - introduction to oops: unit 1
.co
ail
gm

Language Used: PYTHON 3


@
73

Source Code:
8
raj
at

class NumberChecker:
h
ks

def __init__(self, n):


(a

self.n = n
AJ

self.sum = 0
TR

self.temp = n
HA

def check_factorial_sum(self):
S
AK

while self.n:
#..... YOUR CODE STARTS HERE .....

d=self.n%10
if(d==0):
self.sum+=1
else:
f=1
while d>0:
f*=d
d-=1
self.sum+=f
self.n//=10

#..... YOUR CODE ENDS HERE .....

if self.sum == self.temp:
return "Right"
else:
return "Wrong"

if __name__ == "__main__":
n = int(input())
number_checker = NumberChecker(n)
result = number_checker.check_factorial_sum()
print(result)

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:

)
m
< hidden >
.co
ail
Output:
gm
@

Wrong
738

Compilation Status: Passed


raj
at

Execution Time:
h
ks
(a

0.01s
AJ
TR

TestCase2:
HA
S

Input:
AK

< hidden >

Expected Output:
< hidden >

Output:
Wrong

Compilation Status: Passed


Execution Time:
0.01s

16. Gordon the wizard possesses an extraordinary collection of


magical stones. Each stone has a unique weight ranging from 1 to
n.
Gordon's peculiar ability allows him to fuse two stones together, resulting in a new
stone with a weight equal to the sum of the weights of the two original stones.
However, the two original stones vanish after fusion.

Gordon's ultimate goal is to maximize the number of stones that have the same
weight. While it's not mandatory to make all stones uniform in weight, he desires to
have as many stones of equal weight as possible.

Given the number of stones in Gordon's collection, determine how many stones of
equal weight he can create using his magical fusion process.

Input:
The input consists of multiple test cases. The first line contains a single integer t (1 ≤
t ≤ 1000) — the number of test cases.

The following t lines each contain a single integer n (1 ≤ n ≤ 10^9), representing the
number of stones in Gordon's collection.

)
m
.co
Output: ail
gm

For each test case, print a single integer, the maximum number of stones with equal
weight that Gordon can create.
@
73

Sample input:
8
raj
at

110
h
ks

Sample output:
(a
AJ

5
TR
HA
S

Completion Status: Completed


AK

Concepts Included:
gu - introduction to oops: unit 1

Language Used: PYTHON 3

Source Code:
class StoneCalculator:
def __init__(self, t):
self.t = t

def calculate_max_stones(self, n):


#..... YOUR CODE STARTS HERE .....

return n//2
#..... YOUR CODE ENDS HERE .....
if __name__ == "__main__":
t = int(input())
stone_calculator = StoneCalculator(t)

for i in range(t):
n = int(input())
result = stone_calculator.calculate_max_stones(n)
print(result)

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:

)
m
< hidden >
.co
ail
Output:
gm
@

5
738

Compilation Status: Passed


raj
at

Execution Time:
h
ks
(a

0.01s
AJ
TR

TestCase2:
HA
S

Input:
AK

< hidden >

Expected Output:
< hidden >

Output:
13

Compilation Status: Passed


Execution Time:
0.01s

17. Sanjay wants to become the largest of bears, or at least to


become larger than his brother Midhun.
Right now, Sanjay and Midhun weigh a and b respectively. It's guaranteed that
Sanjay's weight is smaller than or equal to his brother's weight.

Sanjay eats a lot and his weight is tripled after every year, while Midhun's weight is
doubled after every year.

After how many full years will Sanjay become strictly larger (strictly heavier) than
Midhun?

Input:
The only line of the input contains two integers a and b (1 ≤ a ≤ b ≤ 10) — the weight
of Sanjay and the weight of Midhun respectively.

Output:
Print one integer, denoting the integer number of years after which Sanjay will
become strictly larger than Midhun.

Sample input:

)
m
47
.co
ail
Sample output:
gm
@

2
738
raj

Completion Status: Completed


h at
ks
(a

Concepts Included:
AJ
TR

gu - introduction to oops: unit 1


HA
S

Language Used: PYTHON 3


AK

Source Code:
class Calculation:
def __init__(self, x, y):
self.x = x
self.y = y

def find_iteration(self):
#..... YOUR CODE STARTS HERE .....

q=0
if(self.x>self.y):
return 1
else:
while self.x<=self.y:
self.x=3*self.x
self.y=2*self.y
q+=1
return q

#..... YOUR CODE ENDS HERE .....

if __name__ == "__main__":
x, y = map(int, input().split())
calculation = Calculation(x, y)
result = calculation.find_iteration()
if result is not None:
print(result)

Compilation Details:

TestCase1:
Input:

)
m
< hidden >

Expected Output: .co


ail
gm

< hidden >


@
73

Output:
8
raj

2
h at
ks

Compilation Status: Passed


(a
AJ

Execution Time:
TR
HA

0.01s
S
AK

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
1

Compilation Status: Passed


Execution Time:
0.009s
18. A group of friends is planning a road trip to visit multiple
destinations. Each friend owns a car, and they need to ensure that
the total fuel consumption of their vehicles matches the distance
they plan to travel. The distance to each destination is represented
by a list of integers, where positive values indicate the distance in
kilometers they need to travel, and negative values indicate the
distance they need to backtrack.
The friends can adjust the fuel levels of their cars by adding or subtracting fuel, with
each adjustment costing one coin. They want to minimize the total cost of adjusting
their fuel levels to match the total distance they plan to travel.

What is the minimum cost the group will have to pay to ensure that the total fuel
consumption of their vehicles equals the total distance they plan to travel?

Input:

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of destinations

)
m
the group plans to visit.
.co
ail
The second line contains n integers a1, a2, ..., an (-10^9 ≤ ai ≤ 10^9) — representing
gm

the distances to each destination. Positive values indicate the distance they need to
@

travel, and negative values indicate the distance they need to backtrack.
738
raj
at

Output:
h
ks

Output a single number — the minimal number of coins you need to pay to make the
(a

product equal to 1.
AJ
TR

Sample input:
HA

40 0 0 0
S
AK

Sample output:

Completion Status: Completed

Concepts Included:
gu - introduction to oops: unit 1

Language Used: PYTHON 3

Source Code:
class NumberProcessor:
def __init__(self, l):
self.l = l
self.s = 0
self.odd = 0
self.nz = 0

def process_numbers(self):
#..... YOUR CODE STARTS HERE .....

for i in range(len(self.l)):
if int(self.l[i])<0:
self.odd+=1
self.s+=abs(-1-int(self.l[i]))
elif int(self.l[i])>0:
self.s+=(int(self.l[i])-1)
else:
self.nz+=1

if self.odd%2!=0:
if "0" in self.l:
return self.s+1*self.nz

)
m
else:

.co
return self.s+2 ail
else:
gm

if "0" in self.l:
@

return self.s+1*self.nz
73

else:
8

return self.s
raj
h at
ks

#..... YOUR CODE ENDS HERE .....


(a
AJ
TR

if __name__ == "__main__":
HA

n = int(input())
S

l = str(input()).split(" ")
AK

number_processor = NumberProcessor(l)
result = number_processor.process_numbers()
print(result)

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
4

Compilation Status: Passed


Execution Time:
0.011s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
13

)
m
.co
Compilation Status: Passed
ail
Execution Time:
gm
@

0.011s
738
raj
at

19. In a college, there are two types of students: Undergraduate and


h
ks

Graduate. Both types of students have a method get_fee() that


(a

returns the tuition fee. However, the tuition fee is calculated


AJ

differently for Undergraduate and Graduate students. For


TR
HA

Undergraduate students, the tuition fee is a fixed amount of $5000.


S

For Graduate students, the tuition fee is the number of credits taken
AK

times $50.
Please write a Python program that defines classes for Undergraduate and Graduate
students, both inheriting from a common Student class. The Student class should
have the get_fee() method, which should be overridden in the Undergraduate and
Graduate classes.

Sample Input:
60

Sample Output:
50003000

Explanation:

The Undergraduate class overrides the get_fee() method and returns a fixed amount
of $5000. The Graduate class also overrides the get_fee() method and returns the
number of credits taken times $50. In the sample input, the Graduate student has
taken 60 credits, so the fee is 60 * $50 = $3000.

Constraints:

The number of credits for a Graduate student is a positive integer.

Completion Status: Completed

Concepts Included:
gu - inheritance and exception handling: unit 2

Language Used: PYTHON 3

Source Code:

)
m
class Student:
#..... YOUR CODE STARTS HERE .....
.co
ail
gm

def __init__(self):
@

pass
73

def get_fee(self):
8
raj

pass
at
h
ks

#..... YOUR CODE ENDS HERE .....


(a
AJ

class Undergraduate(Student):
TR

def get_fee(self):
#..... YOUR CODE STARTS HERE .....
HA
S
AK

return 5000

#..... YOUR CODE ENDS HERE .....

class Graduate(Student):
def __init__(self, credits):
#..... YOUR CODE STARTS HERE .....

self.credits = credits

#..... YOUR CODE ENDS HERE .....

def get_fee(self):
#..... YOUR CODE STARTS HERE .....

return self.credits*50

#..... YOUR CODE ENDS HERE .....


credits = int(input())

undergraduate = Undergraduate()
graduate = Graduate(credits)

programs = [undergraduate, graduate]


for program in programs:
print(program.get_fee())

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

)
m
.co
Output: ail
gm

5000
@

2000
738

Compilation Status: Passed


raj
at

Execution Time:
h
ks
(a

0.01s
AJ
TR

TestCase2:
SHA

Input:
AK

< hidden >

Expected Output:
< hidden >

Output:
5000
5000

Compilation Status: Passed


Execution Time:
0.009s

20. In a B.Tech course, there are several subjects, each with a


different method of evaluation. Some subjects have lab work, some
have project work, and some have only theory exams. Define an
interface Subject with the methods has_lab(), has_project(), and
get_theory_marks(). Then, define three classes LabSubject,
ProjectSubject, and TheorySubject that implement this interface
according to the following rules:

LabSubject returns True for has_lab(), False for has_project(), and a fixed score of 70
for get_theory_marks().

ProjectSubject returns False for has_lab(), True for has_project(), and a fixed score of
80 for get_theory_marks().

TheorySubject returns False for both has_lab() and has_project(), and a fixed score of
90 for get_theory_marks().

Sample Input:

)
m
LabSubject().has_lab()ProjectSubject().has_project()TheorySubject().get_theory_mark
s()
.co
ail
gm

Sample Output:
@
738

TrueTrue90
raj
at

Explanation:
h
ks

The LabSubject class returns True for has_lab(), indicating that the subject has lab
(a

work. The ProjectSubject class returns True for has_project(), indicating that the
AJ

subject has project work. The TheorySubject class returns 90 for get_theory_marks(),
TR

indicating that the theory marks for the subject are 90.
HA
S
AK

Completion Status: Completed

Concepts Included:
gu - inheritance and exception handling: unit 2

Language Used: PYTHON 3

Source Code:
from abc import ABC, abstractmethod

class Subject(ABC):
#..... YOUR CODE STARTS HERE .....

@abstractmethod
def has_lab(self):
pass
@abstractmethod
def has_project(self):
pass
@abstractmethod
def get_theory_marks(self):
pass

#..... YOUR CODE ENDS HERE .....

class LabSubject(Subject):
def has_lab(self):
#..... YOUR CODE STARTS HERE .....

return True

#..... YOUR CODE ENDS HERE .....

def has_project(self):
#..... YOUR CODE STARTS HERE .....

)
m
.co
return False ail
gm

#..... YOUR CODE ENDS HERE .....


@
73

def get_theory_marks(self):
8

#..... YOUR CODE STARTS HERE .....


raj
h at

return 70
ks
(a

#..... YOUR CODE ENDS HERE .....


AJ
TR

class ProjectSubject(Subject):
HA

def has_lab(self):
S

#..... YOUR CODE STARTS HERE .....


AK

return False

#..... YOUR CODE ENDS HERE .....

def has_project(self):
#..... YOUR CODE STARTS HERE .....

return True

#..... YOUR CODE ENDS HERE .....

def get_theory_marks(self):
#..... YOUR CODE STARTS HERE .....

return 80

#..... YOUR CODE ENDS HERE .....


class TheorySubject(Subject):
def has_lab(self):
#..... YOUR CODE STARTS HERE .....

return False

#..... YOUR CODE ENDS HERE .....

def has_project(self):
#..... YOUR CODE STARTS HERE .....

return False

#..... YOUR CODE ENDS HERE .....

def get_theory_marks(self):
#..... YOUR CODE STARTS HERE .....

return 90

)
m
#..... YOUR CODE ENDS HERE .....

.co
ail
def call_func(cls, func):
gm

value = None
@
73

if (func == "has_lab()"):
8

value = cls.has_lab()
raj
hat

elif(func == "has_project()"):
ks

value = cls.has_project()
(a
AJ

elif(func == "get_theory_marks()"):
TR

value = cls.get_theory_marks()
HA
S

return value
AK

# Getting input from the user


lab_class, lab_func = input().strip().split(".")
project_class, project_func = input().strip().split(".")
theory_class, theory_func = input().strip().split(".")

if (lab_class == 'LabSubject()'):
lab = LabSubject()
print(call_func(lab, lab_func))

if(project_class == "ProjectSubject()"):
project = ProjectSubject()
print(call_func(project, project_func))

if(theory_class == "TheorySubject()"):
theory = TheorySubject()
print(call_func(theory, theory_func))
Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
True
True
90

Compilation Status: Passed


Execution Time:

)
m
.co
0.015s ail
gm

TestCase2:
@
73

Input:
8
raj
at

< hidden >


h
ks

Expected Output:
(a
AJ

< hidden >


TR
HA

Output:
S
AK

False
80
False

Compilation Status: Passed


Execution Time:
0.015s

21. In a school, there are several types of staff members: Teachers,


Janitors, and Administrators. All staff members have a method
get_salary() that returns their monthly salary. However, the salary is
calculated differently for each type of staff member. For Teachers,
the salary is a fixed amount of $3000. For Janitors, the salary is a
fixed amount of $2000. For Administrators, the salary is a fixed
amount of $4000.
Write a Python program that defines an abstract class StaffMember with the abstract
method get_salary(). Then, define three classes Teacher, Janitor, and Administrator
that inherit from the StaffMember class and implement the get_salary() method.

Sample Input:
Teacher().get_salary()Janitor().get_salary()Administrator().get_salary()

Sample Output:
300020004000

Explanation:

In this sample, the Teacher class returns a salary of $3000, the Janitor class returns a
salary of $2000, and the Administrator class returns a salary of $4000. This
demonstrates how each class correctly implements the get_salary() method from the
StaffMember abstract base class.

)
m
Completion Status: Completed
.co
ail
gm

Concepts Included:
@
73

gu - inheritance and exception handling: unit 2


8
raj
at

Language Used: PYTHON 3


h
ks
(a

Source Code:
AJ
TR

from abc import ABC, abstractmethod


HA

class StaffMember(ABC):
S
AK

@abstractmethod
def get_salary(self):
pass

#..... YOUR CODE STARTS HERE .....

class Teacher(StaffMember):
def get_salary(self):
return 3000
class Janitor(StaffMember):
def get_salary(self):
return 2000
class Administrator(StaffMember):
def get_salary(self):
return 4000

#..... YOUR CODE ENDS HERE .....

def call_func(cls, func):


value = None
cls_obj = None

if (cls == "Teacher()"):
cls_obj = Teacher()

elif(cls == "Janitor()"):
cls_obj = Janitor()

elif(cls == "Administrator()"):
cls_obj = Administrator()

if (func == "get_salary()"):
value = cls_obj.get_salary()

return value

for _ in range(3):
cls, func = input().strip().split(".")
print(call_func(cls, func))

)
m
Compilation Details: .co
ail
gm
@

TestCase1:
738

Input:
raj
at

< hidden >


h
ks
(a

Expected Output:
AJ
TR

< hidden >


HA

Output:
S
AK

3000
2000
4000

Compilation Status: Passed


Execution Time:
0.01s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >
Output:
3000
4000
2000

Compilation Status: Passed


Execution Time:
0.009s

22. In a sports team, each player has a name and a number of goals
scored. The number of goals scored should always be a non-
negative integer. If a negative value or a non-integer value is
assigned to the number of goals, it should be automatically set to 0.
Please write a Python class Player that has name and goals as attributes. Use the
property decorator to ensure that goals is always a non-negative integer.

)
m
.co
Sample Input 1: ail
gm

John, 510
@

Sample Output 1:
738

John510
raj
at

Sample Input 2:
h
ks
(a

John, 10-5
AJ

Sample Output 2:
TR
HA

John100
S
AK

Explanation:

In the sample input, a Player object is created with the name "John" and 5 goals. The
goals property is then updated to 10, -5, and "hello". When the goals property is set to
a negative value or a non-integer value, the goals.setter method automatically sets
goals to 0. This is why the output is 5, 10, 0, 0. This demonstrates how the property
decorator can be used to control the values of an attribute.

Completion Status: Completed

Concepts Included:
gu - inheritance and exception handling: unit 2

Language Used: PYTHON 3

Source Code:
class Player:
def __init__(self, name, goals=0):
#..... YOUR CODE STARTS HERE .....
self.name=name
self.g=0
if int(goals)>0:
self.g=int(goals)

#..... YOUR CODE ENDS HERE .....

#..... YOUR CODE STARTS HERE .....

@property
def goals(self):
return self.g

@goals.setter
def goals(self,n):
if self.g!=0:
self.g=int(n)

)
m
.co
#..... YOUR CODE ENDS HERE ..... ail
gm

def clean_input(value):
@

return str(value.strip())
738

name, goal = map(clean_input, input().strip().split(","))


raj

next_goal = input()
at
h
ks

player = Player(name, goal)


(a

print(name)
AJ

print(player.goals)
TR

player.goals =next_goal
HA

print(player.goals)
S
AK

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Alice
7
15

Compilation Status: Passed


Execution Time:
0.012s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Bob
0
0

Compilation Status: Passed

)
m
.co
Execution Time: ail
gm

0.017s
@
738

23. You are developing a book management system for a


raj
at

bookstore. The system has a function get_book_details(isbn: str) ->


h
ks

dict that takes an ISBN number as input and returns a dictionary


(a

with book details. The dictionary contains the following keys: 'title',
AJ

'author', 'price', and 'quantity'.


TR
HA

The bookstore has the following books:


S
AK

"Python Programming" by John Doe, ISBN: "1234567890", Price: 500, Quantity: 10

"Data Structures and Algorithms" by Jane Doe, ISBN: "9876543210", Price: 600,
Quantity: 5

"Machine Learning" by Sam Smith, ISBN: "1111111111", Price: 700, Quantity: 2

However, not all books are available in the store at all times. If a book is not available,
the function should raise a ValueError with a message "Book not found".

Write a Python function handle_book_request(isbn: str) -> str that calls


get_book_details(isbn: str) -> dict and handles any ValueError that might be raised.
The function should return a string message about the status of the request.

If the book is found, the function should return a message in the following format:
"Book found: {title} by {author}. Price: {price}, Quantity: {quantity}". If the book is not
found, it should return the message "Book not found".

Constraints:
ISBN is a string of length 10 or 13.

The title, author are strings and price, quantity are integers.

You can't install any external libraries.

Sample Input:
1234567890

Sample Output:
Book found: Python Programming by John Doe. Price: 500, Quantity: 10

Explanation:

In the sample output, that message is returned when the book is found in the
bookstore. The details of the book, including the title, author, price, and quantity, are
displayed in the message. This is done by catching the book details returned by the
get_book_details function in a try block.

)
m
.co
A message, "Book not found", is returned If the book is not found in the bookstore.
ail
This happens when the get_book_details function raises a ValueError. In the except
gm

block, this error is caught and the error message is returned. This demonstrates how
@

error handling works in Python - when an error occurs, instead of the program
73

crashing, the error is caught and handled gracefully. In this case, a meaningful
8

message is returned to the user. This is a key aspect of robust software design.
raj
h at
ks

Completion Status: Completed


(a
AJ
TR

Concepts Included:
HA

gu - inheritance and exception handling: unit 2


S
AK

Language Used: PYTHON 3

Source Code:
def get_book_details(isbn):
books = {
"1234567890": {"title": "Python Programming", "author": "John Doe", "price": 500,
"quantity": 10},
"9876543210": {"title": "Data Structures and Algorithms", "author": "Jane Doe", "price":
600, "quantity": 5},
"1111111111": {"title": "Machine Learning", "author": "Sam Smith", "price": 700,
"quantity": 2},
}
if isbn in books:
return books[isbn]
else:
raise ValueError("Book not found")
def handle_book_request(isbn):
#..... YOUR CODE STARTS HERE .....
try:
book_details = get_book_details(isbn)
return f"Book found: {book_details['title']} by {book_details['author']}. Price:
{book_details['price']}, Quantity: {book_details['quantity']}"
except ValueError as e:
return str(e)

#..... YOUR CODE ENDS HERE .....

isbn = input()
response = handle_book_request(isbn)
print(response)

Compilation Details:

)
m
TestCase1:
.co
ail
Input:
gm

< hidden >


@
73

Expected Output:
8
raj
at

< hidden >


h
ks

Output:
(a
AJ

Book found: Python Programming by John Doe. Price: 500, Quantity: 10


TR
HA

Compilation Status: Passed


S
AK

Execution Time:
0.012s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Book found: Data Structures and Algorithms by Jane Doe. Price: 600, Quantity: 5

Compilation Status: Passed


Execution Time:
0.011s

24. You are developing a product management system for an e-


commerce platform. The system has a function
get_product_details(product_id: str) -> dict that takes a product ID
as input and returns a dictionary with product details. The
dictionary contains the following keys: 'name', 'category', 'price', and
'stock'.
The e-commerce platform has the following products:

"Wireless Mouse", Product ID: "123456", Category: "Electronics", Price: 500, Stock: 10

"Running Shoes", Product ID: "789012", Category: "Sports", Price: 600, Stock: 5

"Coffee Maker", Product ID: "345678", Category: "Home Appliances", Price: 700, Stock:

)
m
2

.co
ail
However, not all products are available on the platform at all times. If a product is not
gm

available, the function should raise an Exception with a message "Product not found".
@
73

Write a Python function handle_product_request(product_id: str) -> str that calls


8
raj

get_product_details(product_id: str) -> dict and handles any Exception that might be
at

raised. The function should return a string message about the status of the request.
h
ks

If the product is found, the function should return a message in the following format:
(a

"Product found: {name}, Category: {category}, Price: {price}, Stock: {stock}". If the
AJ

product is not found, it should return the message "Product not found".
TR
HA

Constraints:
S
AK

Product ID is a string of length 6.

The name, category are strings and price, stock are integers.

You can't install any external libraries.

Sample Input:
901234

Sample Output:
Request handledProduct not found

Explanation:

"Product not found": This message is returned when the product with the ID "901234"
is not found on the platform. In this case, the get_product_details function raises an
Exception with the message "Product not found". This exception is caught in the
handle_product_request function and the error message is returned. This
demonstrates how exception handling works in Python - when an exception occurs,
instead of the program crashing, the exception is caught and handled gracefully. In
this case, a meaningful message is returned to the user.

In all cases, the finally block is executed after the try and except blocks, indicating
that the product request has been processed (Request handled), regardless of
whether an exception was raised or not. This is a key aspect of robust software
design and demonstrates the use of the finally keyword in Python exception handling.

Completion Status: Completed

Concepts Included:
gu - inheritance and exception handling: unit 2

)
Language Used: PYTHON 3

m
.co
ail
Source Code:
gm
@

def get_product_details(product_id):
73

products = {
8

"123456": {"name": "Wireless Mouse", "category": "Electronics", "price": 500, "stock":


raj

10},
at
h

"789012": {"name": "Running Shoes", "category": "Sports", "price": 600, "stock": 5},
ks

"345678": {"name": "Coffee Maker", "category": "Home Appliances", "price": 700,


(a

"stock": 2},
AJ

}
TR

if product_id in products:
HA

return products[product_id]
S

else:
AK

raise Exception("Product not found")

def handle_product_request(product_id):
#..... YOUR CODE STARTS HERE .....
try:
product_details = get_product_details(product_id)
return f"Product found: {product_details['name']}, Category:
{product_details['category']}, Price: {product_details['price']}, Stock:
{product_details['stock']}"
except Exception as e:
return str(e)
finally:
print("Request handled")

#..... YOUR CODE ENDS HERE .....

# Get input from the user


user_input = input()
# Call the handle_product_request function with user input
result = handle_product_request(user_input)
print(result)

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Request handled

)
m
Product found: Wireless Mouse, Category: Electronics, Price: 500, Stock: 10

.co
ail
Compilation Status: Passed
gm

Execution Time:
@
73

0.012s
8
raj
at
h

TestCase2:
ks
(a

Input:
AJ
TR

< hidden >


HA

Expected Output:
S
AK

< hidden >

Output:
Request handled
Product found: Running Shoes, Category: Sports, Price: 600, Stock: 5

Compilation Status: Passed


Execution Time:
0.012s

25. You are required to implement a Python program for managing


employee salaries. The program should define an Employee class
with the following methods:
getInfo(salary, hours_worked): This method takes the salary and the number of hours
worked per day by the employee as input parameters.

AddSal(): This method adds $100 to the salary of the employee if it is less than $500.

AddWorkSal(amount): This method adds a specified amount to the salary of the


employee.

Input:
The input consists of the following:

The first line contains two integers separated by a space: employee_id and option.
employee_id is an integer representing the ID of the employee (always 1 for this
problem). option is an integer representing the selected operation (1 for getInfo(), 2
for AddSal(), and 3 for AddWorkSal()).

If option is 1 (getInfo()), the second line contains two integers separated by a space:
salary (an integer) and hours_worked (an integer).

)
m
if the option is 2, there will be no second line input
.co
ail
If option is 3 (AddWorkSal()), the second line contains an integer amount
gm

representing the amount to be added to the salary.


@
73
8
raj

Output:
h at

Print the following:


ks
(a
AJ

For options 1 and 3, output the final salary of the employee after performing the
TR

operation.
HA

For option 2, print the updated salary


S
AK

Note

The initial salary of the employee is $100.

The final salary of the employee should be output with a '$' symbol.

Sample Input:
1 1200 8

Sample Output:
200$

Input Description:
EmployeeID - 1
Select Function
1.GET INFO
2.ADD SALARY
3.ADD WORK-Salary

Output Description:
employee id
GET INFO
10$
ADD SALARY
20$
ADD WORK-Salary
25$

Completion Status: Completed

Concepts Included:

)
m
.co
GU-INTRODUCTION TO OOP ail
gm

Language Used: PYTHON 3


@
738
raj

Source Code:
h at

class Employee:
ks

def __init__(self):
(a

self.salary = 100 # Initial salary


AJ

self.hours_worked = 0
TR
HA

#..... YOUR CODE STARTS HERE .....


S
AK

def getInfo(self,salary,hours_worked):
self.salary = salary
self.hours_worked = hours_worked

def AddSal(self):
if self.salary<500:
self.salary +=100
def AddWorkSal(self,amount):
self.salary += amount

#..... YOUR CODE ENDS HERE .....

# Main program
employee = Employee()
employee_id, option = map(int, input().split())

if employee_id == 1:
if option == 1:
salary, hours_worked = map(int, input().split())
employee.getInfo(salary, hours_worked)
elif option == 2:
employee.AddSal()
elif option == 3:
amount = int(input())
employee.AddWorkSal(amount)

print(f"{employee.salary}$")

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

)
m
.co
Output: ail
gm

200$
@
73

Compilation Status: Passed


8
raj

Execution Time:
h at
ks

0.01s
(a
AJ

TestCase2:
TR
HA

Input:
S
AK

< hidden >

Expected Output:
< hidden >

Output:
200$

Compilation Status: Passed


Execution Time:
0.009s

26. You are required to implement a notification system for banks


that notifies customers through SMS, Email, and monthly e-
statement. The system consists of an interface Notification with
three methods:

notificationBySms()

notificationByEmail()

notificationByCourier()

Implement two classes, Icici and Hdfc, which implement the Notification interface.
Additionally, create a BankFactory class with two methods:

public Icici getIcici() (returns an object for Icici)

public Hdfc getHdfc() (returns an object for Hdfc)

The main class should get input from the user and display the appropriate notification
based on the bank and notification type selected.

)
Input:

m
.co
The first integer corresponds to the name of the bank, and the next integer
ail
corresponds to the type of notification. If there is no valid input, display 'Invalid input'.
gm
@
73

Output:
8
raj

Output the notification message based on the bank and notification type selected.
at
h
ks

Sample Input:
(a
AJ

11
TR
HA

Sample Output:
S
AK

ICICI - Notification By SMS

Input Description:
11

Output Description:
Welcome to Notification Setup Please select your bank:
1)ICICI
2)HDFC

Enter the type of Notification you want to enter


1)SMS
2)Mail
3)Courier
Completion Status: Completed

Concepts Included:
GU-INTRODUCTION TO OOP

Language Used: PYTHON 3

Source Code:
# Notification interface
class Notification:
def notificationBySms(self):
pass

def notificationByEmail(self):
pass

def notificationByCourier(self):

)
m
pass
.co
ail
# Icici class implementing Notification interface
gm

class Icici(Notification):
@

#..... YOUR CODE STARTS HERE .....


738
raj

def notificationBySms(self):
at

return "ICICI - Notification By SMS"


h
ks
(a

def notificationByEmail(self):
AJ

return "ICICI - Notification By Email"


TR

def notificationByCourier(self):
HA

return "ICICI - Notification By Courier"


S
AK

#..... YOUR CODE ENDS HERE .....

# Hdfc class implementing Notification interface


class Hdfc(Notification):
#..... YOUR CODE STARTS HERE .....

def notificationBySms(self):
return "HDFC - Notification By SMS"

def notificationByEmail(self):
return "HDFC - Notification By Email"

def notificationByCourier(self):
return "HDFC - Notification By Courier"

#..... YOUR CODE ENDS HERE .....

# BankFactory class
class BankFactory:
def getIcici(self):
return Icici()

def getHdfc(self):
return Hdfc()

def main():
bank, notification = map(int, input().split())
bank_factory = BankFactory()

if bank == 1:
bank_obj = bank_factory.getIcici()
elif bank == 2:
bank_obj = bank_factory.getHdfc()
else:
print("Invalid input")
return

if notification == 1:

)
m
print(bank_obj.notificationBySms())

.co
elif notification == 2: ail
print(bank_obj.notificationByEmail())
gm

elif notification == 3:
@

print(bank_obj.notificationByCourier())
73

else:
8

print("Invalid input")
raj
at
h

if __name__ == "__main__":
ks

main()
(a
AJ
TR

Compilation Details:
SHA

TestCase1:
AK

Input:
< hidden >

Expected Output:
< hidden >

Output:
ICICI - Notification By SMS

Compilation Status: Passed


Execution Time:
0.01s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
HDFC - Notification By Courier

Compilation Status: Passed


Execution Time:
0.01s

27. You need to implement a Matrix class with methods to perform


various operations on matrices. The class should have methods for

)
m
the following:
.co
ail
gm

Get the number of rows.


@

Get the number of columns.


738
raj

Set the elements of the matrix at a given position (i, j).


at
h

Multiply two matrices.


ks
(a
AJ

Input:
TR
HA

The input consists of the following:


S
AK

Number of rows for the first matrix (mat1).

Number of columns for the first matrix (mat1).

Values of each element of the first matrix (mat1) in row-major order.

Number of rows for the second matrix (mat2).

Number of columns for the second matrix (mat2).

Values of each element of the second matrix (mat2) in row-major order.

Output:
After inputting both matrices, print each resultant element of the matrix multiplication
in a loop.

Sample Input:
222 2 2 2222 2 2 2

Sample Output:
8888

Input Description:
mat1 rows
<br>mat1 cols
<br>mat1 values of each element (i,j)
<br>mat2 rows
<br>mat2 cols
<br>mat2 values of each element (i,j)

Output Description:
After input of both matrix print the every resultant elements of matrix multiplication in

)
loop

m
.co
ail
Completion Status: Not Completed
gm
@
73

Concepts Included:
8
raj

GU-INTRODUCTION TO OOP
h at
ks

Language Used: PYTHON 3


(a
AJ
TR

Source Code:
HA

class Matrix:
S
AK

#..... YOUR CODE STARTS HERE .....

def __init__(self,rows,cols):
self.rows=rows
self.cols=cols
self.matrix=[[0]*cols

for _ in range(rows)]

def get_rows(self):
return self.rows

def get_cols(self):
return self.cols

def set_elements(self,i,j,value):
self.matrix[i][j]=value

def multiply(self,other):
if self.cols !=other.rows:
print("Invalid")
return None

result=Matrix(self.rows,other.cols)

for i in range(self.rows):
for j in range(self.cols):
for k in range(self.cols):
result.matrix[i][j]+=self.matrix[i][k]*other.matrix[k][j]

return result
#..... YOUR CODE ENDS HERE .....

def main():
mat1_rows = int(input())
mat1_cols = int(input())
mat1_values = list(map(int, input().split()))

mat2_rows = int(input())

)
m
mat2_cols = int(input())

.co
mat2_values = list(map(int, input().split())) ail
gm

if mat1_cols != mat2_rows:
@

print("Invalid")
73

return
8
raj

mat1 = Matrix(mat1_rows, mat1_cols)


hat

mat2 = Matrix(mat2_rows, mat2_cols)


ks
(a

# Set values for matrix 1


AJ

index = 0
TR

for i in range(mat1_rows):
HA

for j in range(mat1_cols):
S

mat1.set_element(i, j, mat1_values[index])
AK

index += 1

# Set values for matrix 2


index = 0
for i in range(mat2_rows):
for j in range(mat2_cols):
mat2.set_element(i, j, mat2_values[index])
index += 1

# Multiply matrices
result = mat1.multiply(mat2)

if result:
for i in range(result.get_rows()):
for j in range(result.get_cols()):
if j+1 == result.get_cols() and i+1 == result.get_rows():
print(result.matrix[i][j], end="")
else:
print(result.matrix[i][j], end=" ")
print()

if __name__ == "__main__":
main()

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
File "script-3.8.1.py", line 32

)
m
return result

.co
^ ail
SyntaxError: 'return' outside function
gm
@
73

Runtime Error (NZEC)


8
raj

Compilation Status: Failed


h at
ks

Execution Time:
(a
AJ

0.01s
TR
HA

TestCase2:
S
AK

Input:
< hidden >

Expected Output:
< hidden >

Output:
File "script-3.8.1.py", line 32
return result
^
SyntaxError: 'return' outside function

Runtime Error (NZEC)

Compilation Status: Failed


Execution Time:
0.01s

28. You are tasked with implementing a credit score calculation


system for banks. Each bank must adhere to rules set by the
Reserve Bank of India (RBI), and any changes made by the RBI must
be universally followed by all banks.
The RBI has announced a new rule: a fixed credit score percentage to be applied to all
transactions. According to this rule, for every transaction, 10% of the transaction
amount will be added to the customer's credit score.

You need to implement a system with the following classes:

Banks: An interface with a method calculateCreditScore() that returns a double.

RBI: A class that implements the Banks interface. It has private data members

)
accountNumber (string), creditScore (double), and holderName (string). It also has a

m
.co
fixed variable CREDIT (double) set to 10%. Implement the calculateCreditScore()
method and a display() method. ail
gm

ICICI: A class that extends RBI.


@
73

HDFC: A class that extends RBI.


8
raj
at

Your task is to implement the required classes and methods to calculate the credit
h
ks

score for a customer based on the given rules. Ensure that the credit score is rounded
(a

to two decimal places.


AJ
TR

Input:
HA
S

The input consists of a single line containing the following space-separated values:
AK

An integer representing the bank: 1 for ICICI, 2 for HDFC.

The holder's name (string).

The account number (string).

The previous credit score (double).

The amount to be paid (double).

Output:
Print the following:

The bank type (string).

The account number (string).


The updated credit score (double, rounded to two decimal places).

A message indicating the credit gained for the payment and the total credit score.

Note

Ensure that the credit score is rounded to two decimal places in the output.

Sample Input:
1 MadhanKumar 218463 652 500

Sample Output:
Hi, MadhanKumar You have gained 50.00 credit score for the payment of 500.0

Your Total Credit Score is 702.00

Input Description:

)
m
.co
Select the Bank Name ail
1.ICICI
gm

2.HDFC
@
738
raj

Enter the Holder Name


h at

Enter the Account Number


ks
(a
AJ

Enter the Previous Credit Score


TR

Enter the Amount to be Paid


HA
S
AK

Output Description:
Bank type

Name

Account Number

Credit score

Amout to be paid

Hi, MadhanKumar You have gained 50.00 credit score for the payment of 500.0
Your Total Credit Score is 702.00

Completion Status: Not Completed

Concepts Included:
GU-INTRODUCTION TO OOP

Language Used: PYTHON 3

Source Code:
class Banks:
def calculateCreditScore(self):
pass

class RBI(Banks):
CREDIT = 0.10

def __init__(self, accountNumber, creditScore, holderName):


self.__accountNumber = accountNumber
self.__creditScore = creditScore
self.__holderName = holderName

def calculateCreditScore(self, amount):

)
m
#..... YOUR CODE STARTS HERE .....

.co
ail
credit_gained = amount* self.CREDIT
gm

self.__creditScore += credit_gained
@

return credit_gained
738

#..... YOUR CODE ENDS HERE .....


raj
at
h

def display(self):
ks

print("Bank type: RBI")


(a

print("Account Number:", self.__accountNumber)


AJ

print("Credit score:", "{:.2f}".format(self.__creditScore))


TR
HA

class ICICI(RBI):
S

def __init__(self, accountNumber, creditScore, holderName):


AK

super().__init__(accountNumber, creditScore, holderName)

def calculateCreditScore(self, amount):


#..... YOUR CODE STARTS HERE .....

credit_gained= super().calculateCreditScore(amount)
print(f"Hi, {self._RBI__holderName} You have gained {credit_gained:.2f} credit score
for the payment of {amount} Your Total Credit Score is {self._RBI__creditscore:.2f}")

#..... YOUR CODE ENDS HERE .....

class HDFC(RBI):
def __init__(self, accountNumber, creditScore, holderName):
super().__init__(accountNumber, creditScore, holderName)

def calculateCreditScore(self, amount):


#..... YOUR CODE STARTS HERE .....

credit_gained= super().calculateCreditScore(amount)
print(f"Hi, {self._RBI__holderName} You have gained {credit_gained:.2f} credit score
for the payment of {amount} Your Total Credit Score is{self._RBI__creditscore:.2f}")

#..... YOUR CODE ENDS HERE .....

class Main:
def __init__(self):
input_data = input().split()
bank = int(input_data[0])
holderName = input_data[1]
accountNumber = input_data[2]
previousCreditScore = float(input_data[3])
amount = float(input_data[4])

if bank == 1:
icici = ICICI(accountNumber, previousCreditScore, holderName)
icici.calculateCreditScore(amount)
elif bank == 2:
hdfc = HDFC(accountNumber, previousCreditScore, holderName)
hdfc.calculateCreditScore(amount)

)
m
else:

.co
print("Invalid bank selection") ail
gm

# Main program execution


@

if __name__ == "__main__":
73

Main()
8
raj
at

Compilation Details:
h
ks
(a

TestCase1:
AJ
TR

Input:
HA
S

< hidden >


AK

Expected Output:
< hidden >

Output:
File "script-3.8.1.py", line 16
credit_gained = amount* self.CREDIT
^
IndentationError: expected an indented block

Runtime Error (NZEC)

Compilation Status: Failed


Execution Time:
0.01s
TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
File "script-3.8.1.py", line 16
credit_gained = amount* self.CREDIT
^
IndentationError: expected an indented block

Runtime Error (NZEC)

Compilation Status: Failed

)
m
.co
Execution Time:
ail
0.01s
gm
@
73

29. In a scenario where banks need to perform confidential fund or


8
raj

message transfers, each bank may utilize its encryption and


h at

decryption techniques. The Reserve Bank provides an interface with


ks
(a

method names, leaving the implementation details to the individual


AJ

banks.
TR
HA

Create an interface BankTransfers.


S
AK

Add two methods with the following prototypes:

public String encrypt(String a);

public String decrypt(String a);

Create a class ICICI which implements the BankTransfers interface and implements a
simple encryption technique.

Create a class HDFC which implements the BankTransfers interface and implements
a simple encryption technique.

Encryption techniques used by both banks:

ICICI: Add 1 to the ASCII value of each character and insert the number '1' after every
character.

HDFC: Add 1 to the ASCII value of characters at even indices and subtract 1 from the
ASCII value of characters at odd indices. Spaces are not encrypted.
The reverse of both techniques will decrypt the message (i.e., original text).

Input:
Bank Type and the message.

Output:
Output the encrypted input.

Sample Input:
1 welcome all

Sample Output:
x1f1m1d1p1n1f1!1b1m1m1

)
m
Input Description:
.co
ail
Select a Bank
gm

Type the user name


@
738

Output Description:
raj
at

Output should have a Encrypted input


h
ks
(a

Completion Status: Completed


AJ
TR
HA

Concepts Included:
S
AK

GU-INTRODUCTION TO OOP

Language Used: PYTHON 3

Source Code:
# Interface for Bank Transfers
class BankTransfers:
def encrypt(self, a):
pass

def decrypt(self, a):


pass

# ICICI class implementing BankTransfers interface


class ICICI(BankTransfers):
#..... YOUR CODE STARTS HERE .....
def encrypt(self,a):
encrypted_message=""
for char in a:
encrypted_message+=chr(ord(char)+1)+"1"
return encrypted_message

def decrypt(self,a):
decrypt_message =""
for i in range(0,len(a),2):
decrypt_message+=che(ord(a[i])-1)
return decrypt_message

#..... YOUR CODE ENDS HERE .....

# HDFC class implementing BankTransfers interface


class HDFC(BankTransfers):
#..... YOUR CODE STARTS HERE .....

def encrypt(self,a):
encrypted_message=""

)
m
for i,char in enumerate(a):

.co
if char !=' ': ail
if i%2==0:
gm

encrypted_message+= chr(ord(char)+1)
@

else:
73

encrypted_message+=chr(ord(char)-1)
8

else:
raj

encrypted_message+=char
hat

return encrypted_message
ks
(a

def decrypt(self,a):
AJ

decrypt_message=""
TR

for i,char in enumerate(a):


HA

if char!=' ':
S

if i%2==0:
AK

decrypt_message+=chr(ord(char)-1)
else:
decrypt_message+=chr(ord(char)+1)
else:
decrypt_message+=char
return decrypted_message

#..... YOUR CODE ENDS HERE .....

# Main function
def main():
bank_type, message = input("").split(maxsplit=1)
bank_type = int(bank_type)

if bank_type == 1:
bank = ICICI()
elif bank_type == 2:
bank = HDFC()
else:
print("Invalid bank type")
return

encrypted_message = bank.encrypt(message)
print(encrypted_message)

# Call the main function


if __name__ == "__main__":
main()

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:

)
m
< hidden >
.co
ail
Output:
gm
@

Tsbsvr ht qdocjmh
738

Compilation Status: Passed


raj
at

Execution Time:
h
ks
(a

0.011s
AJ
TR

TestCase2:
SHA

Input:
AK

< hidden >

Expected Output:
< hidden >

Output:
K1j1n1f1t1i1!1T1i1b1s1n1b1/1Q1

Compilation Status: Passed


Execution Time:
0.009s

30. You are required to implement a class called 'Matrix' containing


a constructor that initializes the number of rows and the number of
columns of a new Matrix object. The Matrix class should have the
following methods:

print_rows(): Print the number of rows of the matrix.

print_cols(): Print the number of columns of the matrix.

print_elements(): Print the elements of the matrix in the form of a 2D array.

If the input is invalid, print 'invalid'.

Input:
The input consists of a single line in the format rowsxcols total_elements, where rows
and cols are integers representing the number of rows and columns of the matrix
respectively, and total_elements is the total number of elements in the matrix. This is
followed by the elements of the matrix, each element separated by a space.

)
Output:

m
.co
Output the number of rows and columns of the matrix on separate lines, followed by
ail
the elements of the matrix in the form of a 2D array.
gm
@

Constraints:
738

The total number of elements in the matrix must equal rows * cols.
raj
h at

Sample Input:
ks
(a

3x3 91 2 34 5 67 8 9
AJ
TR
HA

Sample Output:
S
AK

331 2 34 5 67 8 9

Input Description:
Input matrix size
function
1.no of rows
2.number of col
3.total elements

Output Description:
1x1

Completion Status: Not Completed


Concepts Included:
GU-INTRODUCTION TO OOP

Language Used: PYTHON 3

Source Code:
class Matrix:
#..... YOUR CODE STARTS HERE .....

def __init__(self, rows ,cols):


self.rows=rows
self.cols=cols
self.matrix=[[0]* cols for _ in range (rows)]

def get_rows(self):
return self.rows

)
m
def get_cols(self):

.co
return self.cols ail
gm

def set_element(self, i, j, value):


self.matrix[i][j]= value
@
738

def multiply(self, other):


raj

if self.cols!=other.rows:
at

print("invalid")
h
ks

return None
(a
AJ

result= Matrix(self.rows, other.cols)


TR
HA

for i in range (self.rows):


S

for j in range(other.cols):
AK

for k in range(self.cols):
result.matrix[i][j]+=self.matrix[i][k]*other.matrix[k][j]

return result

#..... YOUR CODE ENDS HERE .....

def main():
try:
# Input
rows_cols, total_elements = input().split()
rows, cols = map(int, rows_cols.split("x"))
total_elements = int(total_elements)

# Validate input
if rows * cols != total_elements:
print("invalid")
return
elements = [list(map(int, input().split())) for _ in range(rows)]

matrix = Matrix(rows, cols, elements)

# Output
matrix.print_rows()
matrix.print_cols()
matrix.print_elements()

except ValueError:
print("invalid")

if __name__ == "__main__":
main()

Compilation Details:

TestCase1:

)
m
Input:
.co
ail
< hidden >
gm

Expected Output:
@
73

< hidden >


8
raj
at

Output:
h
ks

Traceback (most recent call last):


(a

File "script-3.8.1.py", line 59, in <module>


AJ

main()
TR

File "script-3.8.1.py", line 48, in main


HA

matrix = Matrix(rows, cols, elements)


S

TypeError: __init__() takes 3 positional arguments but 4 were given


AK

Runtime Error (NZEC)

Compilation Status: Failed


Execution Time:
0.01s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >
Output:
Traceback (most recent call last):
File "script-3.8.1.py", line 59, in <module>
main()
File "script-3.8.1.py", line 48, in main
matrix = Matrix(rows, cols, elements)
TypeError: __init__() takes 3 positional arguments but 4 were given

Runtime Error (NZEC)

Compilation Status: Failed


Execution Time:
0.01s

31. You are required to implement a program that calculates the

)
m
service tax on every transaction for different types of accounts:
.co
Savings, Checking, and Demat. The service tax rates are 10%, 20%,
ail
and 5% respectively.
gm
@

Create an abstract class Account with three private data member variables:
73

accountNumber of type String, balance of type double, holderName of type String,


8
raj

and methods display() and an abstract method calculateServiceTax() with an


at

argument of type int and return type as double.


h
ks

Create the classes CheckingAccount, SavingsAccount, and DematAccount which


(a

extend the class Account. Use appropriate getters and setters for the above classes.
AJ
TR

Input:
HA
S
AK

The input consists of a single line with the following information separated by space:

Account type (1 for Checking Account, 2 for Savings Account, 3 for Demat Account)

Holder's name

Account number

Current balance

Amount to be transferred

Output:
Output the remaining balance after the transaction.

Sample Input:
3 Rohan 562263 985.32 155
Sample Output:
Your remaining balance is Rs.822.57

Input Description:
Enter the Account Type
1.Checking Account
2.Saving Account
3.Demat Account
1 Enter the Holder Name Jimesh Sharma
Enter the Account Number 23845596HJ
Enter the Current Balance 550
Enter the Amount to be Transfer 200
Transfer Completed Successfully !!!
Holder Name :Jimesh Sharma
Account Number :23845596HJ

Output Description:

)
m
.co
Your remaining balance is Rs.310.00 ail
gm

Completion Status: Not Completed


@
738
raj

Concepts Included:
h at

GU-INTRODUCTION TO OOP
ks
(a
AJ

Language Used: PYTHON 3


TR
HA

Source Code:
S
AK

import java.util.Scanner;

abstract class Account {


private String accountNumber;
private double balance;
private String holderName;

public Account(String accountNumber, double balance, String holderName) {


this.accountNumber = accountNumber;
this.balance = balance;
this.holderName = holderName;
}

public String getAccountNumber() {


return accountNumber;
}

public double getBalance() {


return balance;
}

public void setBalance(double balance) {


this.balance = balance;
}

public String getHolderName() {


return holderName;
}

public void display() {


System.out.println("Holder Name:

Compilation Details:

TestCase1:
Input:

)
m
< hidden >

Expected Output: .co


ail
gm

< hidden >


@
73

Output:
8
raj

File "script-3.6.0.py", line 3


h at

abstract class Account {


ks

^
(a

SyntaxError: invalid syntax


AJ
TR
HA

Runtime Error (NZEC)


S
AK

Compilation Status: Failed


Execution Time:
0.011s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
File "script-3.6.0.py", line 3
abstract class Account {
^
SyntaxError: invalid syntax

Runtime Error (NZEC)

Compilation Status: Failed


Execution Time:
0.011s

32. Mani, renowned for his cryptographic prowess, has developed a


novel encryption technique for transmitting positive integers
securely to his acquaintances. In his method, Mani selects three
secret integers — a, b, and c — from a specified range determined
by lower and upper bounds, denoted as l and r. Subsequently, he
employs the formula m = n * a + b - c to generate the encrypted

)
m
value of the integer n.
.co
ail
However, an adversary has managed to intercept the parameters l, r, and m, posing a
gm

challenge to decrypt the original values of a, b, and c. The task at hand is to decipher
@

any valid combination of a, b, and c that adheres to the following criteria:


738
raj

The values of a, b, and c must be integers.


h at

They must fall within the inclusive range [l, r].


ks
(a

There exists at least one positive integer n such that n * a + b - c equals the
AJ

intercepted value m.
TR
HA

The input comprises multiple test cases, each presenting the intercepted values of l, r,
S

and m. It is assured that at least one feasible solution exists, and any valid
AK

combination of a, b, and c may be outputted if multiple solutions are available.

Sample input:

2010 12 4325 49 15 7 398 9 4416 17 5030 40 975601 801 1000100 102 909599 799
1000503 997 9194 383 590000 100000 70999975000 100000 124999375000
499999 625001375000 500000 624999300000 400000 499999250000 500000
170000 80000 227277025770000 80000 999995334490000 100000 9999955820

Sample output:

11 11 1225 25 495 6 79 8 917 16 1735 35 40800 801 601101 102 102599 601
799503 503 997194 194 383100000 100000 9000199999 100000 75000375000
375000 499999499999 500000 375000399999 400000 300000250000 250001
50000070007 73002 8000070009 80000 7219890003 92499 100000

Completion Status: Completed


Concepts Included:
gu - introduction to oops: unit 1

Language Used: PYTHON 3

Source Code:
import sys

def get_ints():
return map(int, sys.stdin.readline().split())

for _ in range(int(input())):
lst = list(get_ints())

#..... YOUR CODE STARTS HERE .....


l,r,m=lst[0],lst[1],lst[2]
for i in range(l,r+1):

)
m
x1=m%i

.co
x2=i-(m%i) ail
if i<=m and x1<=(r-l):
gm

a=i
b=r
@
73

c=r-x1
8

i=r+2
raj

break
at

elif x2<=(r-l):
h
ks

a=i
(a

b=r-x2
AJ

c=r
TR

i=r+2
HA

break
S

print(a,end=" ")
AK

print(b,end=" ")
print(c)

#..... YOUR CODE ENDS HERE .....

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >
Output:
11 11 12
25 25 49
567
989
17 16 17
35 35 40
800 801 601
101 102 102
599 601 799
503 503 997
194 194 383
100000 100000 90001
99999 100000 75000
375000 375000 499999
499999 500000 375000
399999 400000 300000
250000 250001 500000
70007 73002 80000

)
m
70009 80000 72198

.co
90003 92499 100000 ail
gm

Compilation Status: Passed


@

Execution Time:
738
raj

0.101s
h at
ks

TestCase2:
(a
AJ

Input:
TR
HA

< hidden >


S
AK

Expected Output:
< hidden >

Output:
1 500000 500000
500000 500000 500000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000
499999 500000 375000

Compilation Status: Passed


Execution Time:
0.7s

33. You have been given an array ( a ) containing ( n ) positive


integers.
Your task is to find the minimum number of moves required to transform the array
such that each element is divisible by ( k ) (given).

)
During each move, you can either increase ( x ) by 1 or choose one element ( ai ) from

m
.co
( a ) and increase it by ( x ) (then increase ( x ) by 1). However, you can only perform
the first operation once for each ( i ) from 1 to ( n ). ail
gm

Let's solve ( t ) independent test cases.


@
73

Input:
8
raj
at

The first line contains ( t ) (the number of test cases).


h
ks

For each test case:


(a
AJ

- The first line contains ( n ) and ( k ) (length of ( a ) and required divisor).


TR
HA

- The second line contains ( n ) integers ( a1, a2, ..., an ).


S
AK

Output:

For each test case, print the minimum number of moves required.

Constraints:

( 1 <= t <= 2 times 10^4 )

( 1 <= n <= 2 times 10^5 )

( 1 <= k <= 10^9 )

( 1 <= ai <= 10^9 )

Sample input:

5 4 3 1 2 1 3 10 6 8 7 1 8 3 7 5 10 8 9 5 10 20 100 50 20 100500 10 25 24 24 24
24 24 24 24 24 24 24 8 8 1 2 3 4 5 6 7 8
Sample output:

6 18 0 227 8

Completion Status: Completed

Concepts Included:
gu - introduction to oops: unit 1

Language Used: PYTHON 3

Source Code:
class RemainderCalculator:
def __init__(self, n, k, a):

)
m
self.n = n

.co
self.k = k ail
self.a = a
gm
@

def calculate_remainders(self):
73

rem = {}
8
raj

for num in self.a:


h at

remainder = num % self.k


ks

if remainder != 0:
(a

rem[remainder] = rem.get(remainder, 0) + 1
AJ
TR

return rem
HA
S

def find_maximum_result(self, rem):


AK

result = 0
for r, count in rem.items():
moves = (self.k * (count - 1)) + (self.k - r) + 1
result = max(result, moves)
return result

if __name__ == "__main__":
from sys import stdin

t = int(stdin.readline())

for _ in range(t):
n, k = map(int, stdin.readline().split())
a = list(map(int, stdin.readline().split()))

calculator = RemainderCalculator(n, k, a)
remainders = calculator.calculate_remainders()
print(calculator.find_maximum_result(remainders))
Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
6
18
0
227
8

Compilation Status: Passed

)
m
.co
Execution Time: ail
gm

0.011s
@
73

TestCase2:
8
raj
at

Input:
h
ks
(a

< hidden >


AJ

Expected Output:
TR
HA

< hidden >


S
AK

Output:
6

Compilation Status: Passed


Execution Time:
0.012s

34. The Felicity Committee assigns a power value to each


superhero, and the Avengers aim to maximize their team's average
power through strategic operations.
Initially, the Avengers have n superheroes with powers a1, a2, ..., an. In each
operation, they can either remove a superhero (if there are at least two) or increase a
superhero's power by 1.

They are allowed a maximum of m operations, with each superhero limited to k power
increases. Can you assist the Avengers in maximizing their team's average power

Input:
The first line contains three integers n, k and m (1≤n≤105, 1≤k≤105, 1≤m≤107) — the
number of superheroes, the maximum number of times you can increase power of a
particular superhero, and the total maximum number of operations.

The second line contains n integers a1,a2,…,an (1≤ai≤106) — the initial powers of the
superheroes in the cast of avengers.

Output:
Output a single number — the maximum final average power.

Your answer is considered correct if its absolute or relative error does not exceed
10−6.

Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if
and only if |a−b|max(1,|b|)≤10−6.

)
m
Sample input:
.co
ail
2 4 64 7
gm
@

Sample output:
738

11.0
raj
h at
ks

Completion Status: Completed


(a
AJ
TR

Concepts Included:
HA

gu - introduction to oops: unit 1


S
AK

Language Used: PYTHON 3

Source Code:
n, k, m = map(int, input().split())
a = list(map(int, input().split()))

#..... YOUR CODE STARTS HERE .....

a.sort()
ans=sum(a)
r=0
for i in range(n):
if i<=m:
r=int(max(r,(ans+min(k*(n-i),m-i))/(n-i)))
ans-=a[i]
print(r)
#..... YOUR CODE ENDS HERE .....

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
11

Compilation Status: Passed

)
Execution Time:

m
0.011s .co
ail
gm
@

TestCase2:
738

Input:
raj
at

< hidden >


h
ks
(a

Expected Output:
AJ
TR

< hidden >


HA

Output:
S
AK

Compilation Status: Passed


Execution Time:
0.011s

35. Sanjay is a student who hates maths. But he was a good


programmer. There was a sum in second chapter which was given
to him as a homework.Help him to finish his homework.
You are given with a number n. You have to find the sum of numbers from 1 to n and
subtract all the 2nd values from the sum. Help him to finish the exercise in the second

chapter. Write a program to finish the maths homework.

Input:
The first line contains an integer t, the total number of testcases.

The next t lines contain an integer n.

Input Constraints:1<=t<=1001<=n<=10^9

Output:
Print t lines of integer values

Sample input:

241000000000

Sample output:

-4499999998352516354

Completion Status: Completed

)
m
.co
Concepts Included: ail
gm

gu - introduction to oops: unit 1


@
73

Language Used: PYTHON 3


8
raj
hat

Source Code:
ks
(a

import math
AJ
TR

class NumberCalculator:
HA

def __init__(self):
S

pass
AK

def calculate_result(self, n):


return n * (n + 1) // 2 - 2 * (2 ** (int(math.log2(n)) + 1) - 1)

if __name__ == "__main__":
number_calculator = NumberCalculator()
test_cases = int(input())

for i in range(test_cases):
n = int(input())
result = number_calculator.calculate_result(n)
print(result)

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
-4
499999998352516354

Compilation Status: Passed


Execution Time:
0.011s

TestCase2:
Input:

)
m
< hidden >

Expected Output: .co


ail
gm

< hidden >


@
73

Output:
8
raj

61
hat

909
ks

3285271
(a
AJ

Compilation Status: Passed


TR
HA

Execution Time:
S
AK

0.012s

36. You are given a positive integer 'n'. Your task is to find all unique
combinations of positive integers that multiply together to give 'n'. A
combination is considered unique if there is no way to reorder it to
get a different combination. The integers in each combination
should be in non-decreasing order.
Your goal is to implement a function that generates these combinations for a given
value of 'n'.

Input:

An integer 'n' (2 ≤ n ≤ 30), representing the number to factorize.


Output:

A list of lists, where each inner list contains a unique combination of integers greater
than 1 that multiply to 'n'. The inner lists should be sorted in ascending order, and the
outer list should also be sorted based on the first element of each inner list.

Constraints:

At least one valid combination exists for the given 'n'.

Sample Input:
8

Sample Output:
[[2, 2, 2], [2, 4], [1, 8]]

)
m
.co
ail
Completion Status: Completed
gm
@

Concepts Included:
738
raj

gu - introduction to oops: unit 1


h at
ks

Language Used: PYTHON 3


(a
AJ
TR

Source Code:
HA

class FactorFinder:
S
AK

def __init__(self, n):


self.n = n

def find_factors(self):
def backtrack(remaining, start, path, result):
if remaining == 1:
if len(path) > 1:
result.append(path[:])
else:
result.append([1, path[0]])
return
for i in range(start, remaining + 1):
if remaining % i == 0:
path.append(i)
backtrack(remaining // i, i, path, result)
path.pop()

result = []
backtrack(self.n, 2, [], result)
return result

if __name__ == '__main__':
n = int(input())
factor_finder = FactorFinder(n)
print(factor_finder.find_factors())

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:

)
m
.co
[[2, 2, 2], [2, 4], [1, 8]] ail
gm

Compilation Status: Passed


@

Execution Time:
738
raj

0.013s
h at
ks

TestCase2:
(a
AJ

Input:
TR
HA

< hidden >


S
AK

Expected Output:
< hidden >

Output:
[[1, 23]]

Compilation Status: Passed


Execution Time:
0.012s

37. You are developing a simple calculator in Python. The calculator


has a function calculate(operation: str, num1: float, num2: float) ->
float that takes an operation and two numbers as input and returns
the result of the operation. The operation can be one of the
following: 'add', 'subtract', 'multiply', 'divide'.
However, not all operations are valid. If an invalid operation is passed, the function
should raise a ValueError with a message "Invalid operation".

Also, if the operation is 'divide' and the second number is 0, the function should raise
a ZeroDivisionError with a message "Cannot divide by zero".

Write a Python function handle_calculation(operation: str, num1: float, num2: float) ->
str that calls calculate(operation: str, num1: float, num2: float) -> float and handles
any ValueError or ZeroDivisionError that might be raised. The function should return a
string message about the status of the calculation.

Constraints:

num1 and num2 are floats.

You can't install any external libraries.

Sample Input:

)
m
.co
add, 1.0, 2.0 ail
gm

Sample Output:
@
73

Result: 3.0
8
raj
at

Explanation:
h
ks

The result of the operation is displayed in the message.


(a
AJ
TR

Completion Status: Completed


SHA
AK

Concepts Included:
gu - inheritance and exception handling: unit 2

Language Used: PYTHON 3

Source Code:

def calculate(operation, num1, num2):


if operation == 'add':
return num1 + num2
elif operation == 'subtract':
return num1 - num2
elif operation == 'multiply':
return num1 * num2
elif operation == 'divide':
if num2 == 0:
raise ZeroDivisionError("Cannot divide by zero")
return num1 / num2
else:
raise ValueError("Invalid operation")

def handle_calculation(operation, num1, num2):


#..... YOUR CODE STARTS HERE .....
try:
result = calculate(operation, num1, num2)
return f"Result: {result}"
except ValueError as ve:
return str(ve)
except ZeroDivisionError as zde:
return str(zde)

#..... YOUR CODE ENDS HERE .....

def main():
inputs = input()

)
m
operation, num1, num2 = map(str.strip, inputs.split(","))

.co
num1 = float(num1) ail
num2 = float(num2)
gm
@

message = handle_calculation(operation, num1, num2)


73

print(message)
8
raj

if __name__ == "__main__":
at
h

main()
ks
(a
AJ

Compilation Details:
TR
HA

TestCase1:
S
AK

Input:
< hidden >

Expected Output:
< hidden >

Output:
Result: 6.0

Compilation Status: Passed


Execution Time:
0.012s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Result: 5.0

Compilation Status: Passed


Execution Time:
0.013s

38. You are developing a stock management system for a market.


The system has a function get_stock(item: str) -> int that takes an

)
m
item name as input and returns the quantity of that item in stock.
.co
ail
The market has the following items in stock:
gm
@

"Apples" - 50
738
raj

"Oranges" - 30
h at

"Grapes" - 0
ks
(a
AJ

However, not all items are available in the market at all times. If an item is not
TR

available, the function should raise a custom exception ItemNotFoundError with a


HA

message "Item not found".


S
AK

Write a Python function handle_stock_request(item: str) -> str that calls


get_stock(item: str) -> int and handles any ItemNotFoundError that might be raised.
The function should return a string message about the status of the request.

If the item is found and the stock is greater than 0, the function should return a
message in the following format: "Stock for {item}: {stock}". If the item is not found or
the stock is 0, it should return the message "Item not found".

Constraints:

Item is a string.

You can't install any external libraries.

Sample Input:
Apples
Sample Output:
Stock for Apples: 50

Explanation:

In the sample outputs, the message is returned when the item is found in the market
and the stock is greater than 0. The stock quantity of the item is displayed in the
message. This is done by catching the stock quantity returned by the get_stock
function in a try block.

Completion Status: Completed

Concepts Included:
gu - inheritance and exception handling: unit 2

Language Used: PYTHON 3

)
m
.co
Source Code: ail
gm

class ItemNotFoundError(Exception):
pass
@
738

def get_stock(item):
raj

stock = {
h at

"Apples": 50,
ks

"Oranges": 30,
(a

"Grapes": 0,
AJ

}
TR

if item in stock:
HA

return stock[item]
S

else:
AK

raise ItemNotFoundError("Item not found")

def handle_stock_request(item):
#..... YOUR CODE STARTS HERE .....

try:
stock = get_stock(item)
if stock > 0:
return f"Stock for {item}: {stock}"
else:
return "Item not found"
except ItemNotFoundError:
return "Item not found"

#..... YOUR CODE ENDS HERE .....

user_input = input()

print(handle_stock_request(user_input))
Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Stock for Apples: 50

Compilation Status: Passed


Execution Time:
0.011s

)
m
TestCase2: .co
ail
gm

Input:
@
73

< hidden >


8
raj

Expected Output:
hat
ks

< hidden >


(a
AJ

Output:
TR

Stock for Oranges: 30


HA
S

Compilation Status: Passed


AK

Execution Time:
0.011s

39. Design a Python program that uses multiple inheritance to


model an e-commerce platform. The platform sells two types of
products: physical products and digital products. Both types of
products have a name and a price. However, a physical product also
has a shipping weight, while a digital product has a file size.
Create classes to represent both types of products and use multiple inheritance to
create a third class that represents a product that is both physical and digital (for
example, a video game that can be purchased as a physical disc or downloaded
digitally).

Write a method in each class to print the details of the product.


Sample Input:
Book, 9.99, 1.0Ebook, 6.99, 2Video Game, 59.99, 0.2, 25

Sample Output:
Physical Product: Book, Price: $9.99, Shipping Weight: 1.0 kgDigital Product: Ebook,
Price: $6.99, File Size: 2 MBHybrid Product: Video Game, Price: $59.99, Shipping
Weight: 0.2 kg, File Size: 25 GB

Explanation:

In the sample output, each line represents the details of a product:

The first line is the details of a physical product. It’s a book with a price of $9.99 and a
shipping weight of 1.0 kg.

The second line is the details of a digital product. It’s an Ebook with a price of $6.99
and a file size of 2 MB.

)
The third line is the details of a hybrid product. It’s a video game with a price of

m
$59.99, a shipping weight of 0.2 kg, and a file size of 25 GB.
.co
ail
gm

These details are printed by calling the print_details() method of each product object.
@

The method is defined in each class and prints the details specific to that class. For
73

the HybridProduct class, which inherits from both PhysicalProduct and


8

DigitalProduct, the print_details() method prints the details of both the physical and
raj

digital aspects of the product.


at
h
ks
(a

Completion Status: Completed


AJ
TR
HA

Concepts Included:
S
AK

gu - inheritance and exception handling: unit 2

Language Used: PYTHON 3

Source Code:
class Product:
def __init__(self, name, price):
#..... YOUR CODE STARTS HERE .....
self.name= name
self.price= price

#..... YOUR CODE ENDS HERE .....

class PhysicalProduct(Product):
def __init__(self, name, price, weight):
#..... YOUR CODE STARTS HERE .....
self.weight= weight
super().__init__(name,price)

#..... YOUR CODE ENDS HERE .....

def print_details(self):
#..... YOUR CODE STARTS HERE .....
print(f"Physical Product: {self.name}, Price: ${self.price}, Shipping Weight:
{self.weight} kg")

#..... YOUR CODE ENDS HERE .....

class DigitalProduct(Product):
def __init__(self, name, price, file_size):
#..... YOUR CODE STARTS HERE .....
self.name=name
self.price=price

)
m
self.file_size= file_size

.co
ail
gm

#..... YOUR CODE ENDS HERE .....


@
73

def print_details(self):
8

#..... YOUR CODE STARTS HERE .....


raj

print(f"Digital Product: {self.name}, Price: ${self.price}, File Size: {self.file_size} MB")


h at
ks
(a

#..... YOUR CODE ENDS HERE .....


AJ
TR

class HybridProduct(PhysicalProduct, DigitalProduct):


HA

def __init__(self, name, price, weight, file_size):


S

#..... YOUR CODE STARTS HERE .....


AK

self.name=name
self.price=price
self.weight= weight
self.file_size= file_size

#..... YOUR CODE ENDS HERE .....

def print_details(self):
#..... YOUR CODE STARTS HERE .....
print(f"Hybrid Product: {self.name}, Price: ${self.price}, Shipping Weight: {self.weight}
kg, File Size: {self.file_size} GB")

#..... YOUR CODE ENDS HERE .....

def clean_input(value):
return str(value.strip())
if __name__ == '__main__':
pp_name, pp_price, shipping_weight = map(clean_input, input().strip().split(','))
physical_product = PhysicalProduct(pp_name, pp_price, shipping_weight)

dp_name, dp_price, file_size = map(clean_input, input().strip().split(','))


digital_product = DigitalProduct(dp_name, dp_price, file_size)

hp_name, hp_price, hp_shipping_weight, hp_file_size = map(clean_input,


input().strip().split(','))
hybrid_product = HybridProduct(hp_name, hp_price, hp_shipping_weight, hp_file_size)

physical_product.print_details()
digital_product.print_details()
hybrid_product.print_details()

Compilation Details:

)
m
TestCase1:
.co
ail
Input:
gm

< hidden >


@
73

Expected Output:
8
raj
at

< hidden >


h
ks

Output:
(a
AJ

Physical Product: Laptop, Price: $599.99, Shipping Weight: 2.5 kg


TR

Digital Product: Software, Price: $199.99, File Size: 500 MB


HA

Hybrid Product: Video Game, Price: $59.99, Shipping Weight: 0.2 kg, File Size: 25 GB
S
AK

Compilation Status: Passed


Execution Time:
0.012s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Physical Product: Camera, Price: $299.99, Shipping Weight: 1.0 kg
Digital Product: Photography Course, Price: $49.99, File Size: 2000 MB
Hybrid Product: Music Album, Price: $19.99, Shipping Weight: 0.1 kg, File Size: 2 GB

Compilation Status: Passed


Execution Time:
0.011s

40. Design a Python program that uses hierarchical inheritance to


model electronic devices. There are two types of electronic devices:
Mobiles and Laptops. Both Mobiles and Laptops have a brand name
and a price. However, a Mobile also has a screen size, while a
Laptop has a screen resolution.
Create classes to represent both types of devices and use hierarchical inheritance to
avoid code duplication. Write a method in each class to print the details of the device.

Sample Input:

)
m
.co
Samsung Galaxy S21, 799.99, 6.2 inchesDell XPS 13, 999.99, 1920 x 1080
ail
gm

Sample Output:
@
73

Mobile: Samsung Galaxy S21, Price: $799.99, Screen Size: 6.2 inchesLaptop: Dell XPS
8
raj

13, Price: $999.99, Screen Resolution: 1920 x 1080


hat

Explanation:
ks
(a

In the sample output, each line represents the details of an electronic device:
AJ
TR

The first line is the details of a mobile. It's a Samsung Galaxy S21 with a price of
HA

$799.99 and a screen size of 6.2 inches.


S
AK

The second line is the details of a laptop. It's a Dell XPS 13 with a price of $999.99
and a screen resolution of 1920 x 1080.

These details are printed by calling the print_details() method of each device object.
The method is defined in each class and prints the details specific to that device.

This is an example of hierarchical inheritance, where the Mobile and Laptop classes
inherit from a common base class (ElectronicDevice). The base class defines
properties and methods common to all electronic devices (like name and price), while
the derived classes add properties and methods specific to mobiles and laptops (like
screen_size and screen_resolution).

Constraints:

The name of the mobile or laptop is a string and can contain any printable ASCII
characters.

The price of the mobile or laptop is a float and can be any positive number.
The screen size of the mobile is a string and can contain any printable ASCII
characters.

The screen resolution of the laptop is a string and can contain any printable ASCII
characters.

Completion Status: Completed

Concepts Included:
gu - inheritance and exception handling: unit 2

Language Used: PYTHON 3

Source Code:

)
m
class ElectronicDevice:

.co
def __init__(self, name, price): ail
#..... YOUR CODE STARTS HERE .....
gm

self.name = name
@

self.price = price
73
8
raj

#..... YOUR CODE ENDS HERE .....


at
h
ks

class Mobile(ElectronicDevice):
(a

def __init__(self, name, price, screen_size):


AJ

#..... YOUR CODE STARTS HERE .....


TR

super().__init__(name, price)
HA

self.screen_size = screen_size
S
AK

#..... YOUR CODE ENDS HERE .....

def print_details(self):
#..... YOUR CODE STARTS HERE .....
return f"Mobile: {self.name}, Price: ${self.price}, Screen Size: {self.screen_size}"

#..... YOUR CODE ENDS HERE .....

class Laptop(ElectronicDevice):
def __init__(self, name, price, screen_resolution):
#..... YOUR CODE STARTS HERE .....
super().__init__(name, price)
self.screen_resolution = screen_resolution

#..... YOUR CODE ENDS HERE .....


def print_details(self):
#..... YOUR CODE STARTS HERE .....

return f"Laptop: {self.name}, Price: ${self.price}, Screen Resolution:


{self.screen_resolution}"

#..... YOUR CODE ENDS HERE .....

# Get sample input from the user


mobile_input = input().split(", ")
laptop_input = input().split(", ")

# Create objects
mobile = Mobile(*mobile_input)
laptop = Laptop(*laptop_input)

# Print details
print(mobile.print_details())
print(laptop.print_details())

)
m
Compilation Details:
.co
ail
gm

TestCase1:
@
73

Input:
8
raj

< hidden >


hat
ks

Expected Output:
(a
AJ

< hidden >


TR

Output:
SHA

Mobile: iPhone 13, Price: $1099.00, Screen Size: 6.1 inches


AK

Laptop: MacBook Pro, Price: $2399.00, Screen Resolution: 3072 x 1920

Compilation Status: Passed


Execution Time:
0.012s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Mobile: Google Pixel 6, Price: $599.00, Screen Size: 6.4 inches
Laptop: Dell XPS 15, Price: $1749.99, Screen Resolution: 3840 x 2400

Compilation Status: Passed


Execution Time:
0.018s

41. Design a Python program that uses single level inheritance to


model a school. The school has two types of people: students and
teachers. Both students and teachers have a name and an age.
However, a student also has a department, while a teacher has a
subject they teach.
Create classes to represent both a student and a teacher, and use inheritance to
avoid code duplication. Write a method in each class to print the details of the
student or teacher.

)
m
.co
Sample Input: ail
gm

Ravi Kumar, 20, Computer ScienceDr. Srinivasan, 45, Data Structures and Algorithms
@
73

Sample Output:
8
raj
at

Student: Ravi Kumar, Age: 20, Department: Computer ScienceTeacher: Dr. Srinivasan,
h

Age: 45, Subject: Data Structures and Algorithms


ks
(a

Explanation:
AJ
TR

In the sample output, each line represents the details of a person in the school:
SHA

The first line is the details of a student. It's Ravi Kumar who is 20 years old and
AK

studying Computer Science.

The second line is the details of a teacher. It's Dr. Srinivasan who is 45 years old and
teaches Data Structures and Algorithms.

These details are printed by calling the print_details() method of each person object.
The method is defined in each class and prints the details specific to that person.

This is an example of single level inheritance, where the Student and Teacher classes
inherit from a common base class (Person). The base class defines properties and
methods common to all people (like name and age), while the derived classes add
properties and methods specific to students and teachers (like grade and subject).

Constraints:

The name of the student or teacher is a string and can contain any printable ASCII
characters.

The age of the student or teacher is an integer and can be any positive integer.
The department of the student is a string and can contain any printable ASCII
characters.

The subject of the teacher is a string and can contain any printable ASCII characters.

Completion Status: Completed

Concepts Included:
gu - inheritance and exception handling: unit 2

Language Used: PYTHON 3

Source Code:

class Person:

)
m
def __init__(self, name, age):

.co
self.name = name ail
self.age = age
gm
@

def print_details(self):
73

pass
8
raj
h at

class Student(Person):
ks

def __init__(self, name, age, department):


(a

#..... YOUR CODE STARTS HERE .....


AJ

super().__init__(name, age)
TR

self.department = department
HA
S
AK

#..... YOUR CODE ENDS HERE .....

def print_details(self):
#..... YOUR CODE STARTS HERE .....

print(f"Student: {self.name}, Age: {self.age}, Department: {self.department}")

#..... YOUR CODE ENDS HERE .....

class Teacher(Person):
def __init__(self, name, age, subject):
#..... YOUR CODE STARTS HERE .....
super().__init__(name, age)
self.subject = subject

#..... YOUR CODE ENDS HERE .....


def print_details(self):
#..... YOUR CODE STARTS HERE .....

print(f"Teacher: {self.name}, Age: {self.age}, Subject: {self.subject}")

#..... YOUR CODE ENDS HERE .....

def main():
# Sample Input
student_info = input().split(", ")
teacher_info = input().split(", ")

# Create objects
student = Student(*student_info)
teacher = Teacher(*teacher_info)

# Print details
student.print_details()
teacher.print_details()

)
m
.co
ail
if __name__ == "__main__":
gm

main()
@
73

Compilation Details:
8
raj
h at

TestCase1:
ks
(a

Input:
AJ
TR

< hidden >


HA

Expected Output:
S
AK

< hidden >

Output:
Student: Ravi Kumar, Age: 20, Department: Computer Science
Teacher: Dr. Srinivasan, Age: 45, Subject: Data Structures and Algorithms

Compilation Status: Passed


Execution Time:
0.017s

TestCase2:
Input:
< hidden >
Expected Output:
< hidden >

Output:
Student: Priya, Age: 21, Department: Electronics and Communication
Teacher: Prof. Ramanujan, Age: 50, Subject: Digital Signal Processing

Compilation Status: Passed


Execution Time:
0.012s

42. Consider an e-commerce application that uses a class hierarchy


to represent different types of products. We have a base class
Product and two subclasses Book and Electronics. Both Book and
Electronics classes override a method get_details() from the

)
m
Product class. Now, we have a new product type EBook that is both
.co
a Book and an Electronics. The EBook class inherits from both Book
ail
gm

and Electronics.
@

Write a Python function mro_sequence(cls) that takes a class cls as input and returns
73

the Method Resolution Order (MRO) for that class as a list of class names.
8
raj
hat

Sample Input:
ks
(a

EBook
AJ
TR

Sample Output:
SHA
AK

['EBook', 'Book', 'Electronics', 'Product', 'object']

Explanation:

In Python, the Method Resolution Order (MRO) is the order in which the base classes
are searched when executing a method. Python uses an algorithm called C3
Linearization, or just C3, to compute this order. In the given example, the MRO for
class EBook is EBook -> Book -> Electronics -> Product -> object.

Constraints:

The input class cls is a valid Python class.

The class hierarchy can have multiple levels of inheritance but does not contain any
circular inheritance.

Completion Status: Completed


Concepts Included:
gu - inheritance and exception handling: unit 2

Language Used: PYTHON 3

Source Code:

class Product:
def get_details(self):
pass

class Book(Product):
def get_details(self):
pass

class Electronics(Product):
def get_details(self):

)
m
pass

.co
ail
class EBook(Book, Electronics):
gm

pass
@
73

class Apparel(Product):
8

pass
raj
at

class SmartWatch(Apparel, Electronics):


h
ks

pass
(a
AJ

class Furniture(Product):
TR

pass
HA
S

class SmartFurniture(Furniture, Electronics):


AK

pass

class Organic(Product):
pass

class Grocery(Product):
pass

class OrganicGrocery(Grocery, Organic):


pass

def mro_sequence(cls):
#..... YOUR CODE STARTS HERE .....

return [c.__name__ for c in cls.mro()]

#..... YOUR CODE ENDS HERE .....

class_name = input()
cls = globals()[class_name]

# Print the MRO sequence


print(mro_sequence(cls))

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:

)
m
['EBook', 'Book', 'Electronics', 'Product', 'object']

.co
ail
Compilation Status: Passed
gm

Execution Time:
@
73

0.012s
8
raj
hat

TestCase2:
ks
(a

Input:
AJ
TR

< hidden >


HA

Expected Output:
S
AK

< hidden >

Output:
['SmartWatch', 'Apparel', 'Electronics', 'Product', 'object']

Compilation Status: Passed


Execution Time:
0.012s

43. Consider an election scenario where we have different roles


such as Citizen, Politician, and PublicServant. Both Politician and
PublicServant are subclasses of Citizen. Now, we have a new role
Mayor who is both a Politician and a PublicServant. The Mayor
class inherits from both Politician and PublicServant.
Each of these classes has a method role_duties() that describes the duties of the
role. However, when a Mayor object calls this method, which method should it
execute? This is known as the Diamond Problem.

Write a Python function mro_sequence(cls) that takes a class cls as input and returns
the Method Resolution Order (MRO) for that class as a list of class names.

Sample Input:
Mayor

Sample Output:
['Mayor', 'Politician', 'PublicServant', 'Citizen', 'object']

Explanation:

In Python, the Method Resolution Order (MRO) is the order in which the base classes
are searched when executing a method. Python uses an algorithm called C3
Linearization, or just C3, to compute this order. In the given example, the MRO for

)
m
class Mayor is Mayor -> Politician -> PublicServant -> Citizen -> object. This means

.co
that if a Mayor object calls the role_duties() method, it will first look for this method in
ail
the Mayor class. If it doesn't find it there, it will look in the Politician class, then in the
gm

PublicServant class, and finally in the Citizen class.


@

Constraints:
73
8
raj

The input class cls is a valid Python class.


at
h
ks

The class hierarchy can have multiple levels of inheritance but does not contain any
(a

circular inheritance.
AJ
TR
HA

Completion Status: Completed


S
AK

Concepts Included:
gu - inheritance and exception handling: unit 2

Language Used: PYTHON 3

Source Code:

class Citizen:
def role_duties(self):
return "Citizen duties"

class Politician(Citizen):
def role_duties(self):
return "Politician duties"
class PublicServant(Citizen):
def role_duties(self):
return "Public servant duties"

class Mayor(Politician, PublicServant):


def role_duties(self):
return "Mayor duties"

class Voter(Citizen):
def role_duties(self):
return "Voter duties"

class Candidate(Citizen):
def role_duties(self):
return "Candidate duties"

class ElectedOfficial(Voter, Candidate):


def role_duties(self):
return "Elected official duties"

)
m
.co
class Activist(Citizen): ail
def role_duties(self):
gm

return "Activist duties"


@
73

class ActivistPolitician(Activist, Politician):


8

def role_duties(self):
raj

return "Activist politician duties"


at
h
ks

class Worker(Citizen):
(a

def role_duties(self):
AJ

return "Worker duties"


TR
HA

class WorkingPolitician(Worker, Politician):


S

def role_duties(self):
AK

return "Working politician duties"

def mro_sequence(cls):
#..... YOUR CODE STARTS HERE .....

return [c.__name__ for c in cls.mro()]

#..... YOUR CODE ENDS HERE .....

class_name = input()

cls = globals()[class_name]

# Print the MRO sequence


print(mro_sequence(cls))

Compilation Details:
TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
['Mayor', 'Politician', 'PublicServant', 'Citizen', 'object']

Compilation Status: Passed


Execution Time:
0.015s

TestCase2:

)
m
.co
Input: ail
gm

< hidden >


@

Expected Output:
73
8
raj

< hidden >


at
h

Output:
ks
(a

['ElectedOfficial', 'Voter', 'Candidate', 'Citizen', 'object']


AJ
TR

Compilation Status: Passed


HA

Execution Time:
S
AK

0.011s

44. Design a Python program that uses multilevel inheritance to


model the administrative divisions of Tamil Nadu. Tamil Nadu is
divided into districts, and each district is divided into cities. All
divisions have a name and a population. However, a district also has
a number of cities, and Tamil Nadu has a number of districts.
Create classes to represent Tamil Nadu, a district, and a city, and use multilevel
inheritance to avoid code duplication. Write a method in each class to print the details
of the division.

Sample Input:
Coimbatore, 1064000Coimbatore District, 3472578, 2Tamil Nadu, 77841267, 38
Sample Output:
City: Coimbatore, Population: 1064000District: Coimbatore District, Population:
3472578, Number of Cities: 2State: Tamil Nadu, Population: 77841267, Number of
Districts: 38

Explanation:

Multilevel inheritance is used to model the hierarchical relationship between a state,


its districts, and the cities within those districts.

The City class is the base level in this hierarchy. It has properties like name and
population.

The District class inherits from the City class, making it the next level in the hierarchy.
It has all the properties of a City, plus an additional property: the number of cities.
When we create a District object and call its print_details() method, it prints the
details specific to that district, including the number of cities.

The TamilNadu class inherits from the District class, making it the top level in the
hierarchy. It has all the properties of a District, plus an additional property: the number

)
m
of districts. When we create a TamilNadu object and call its print_details() method, it
.co
prints the details specific to the state, including the number of districts.
ail
gm

This is an example of multilevel inheritance, where a derived class inherits from a


@

base class, which in turn inherits from another base class. In this case, TamilNadu is
738

a derived class that inherits from District, which is a derived class that inherits from
raj

City.
at
h
ks

Constraints:
(a
AJ

The name of the city, district, or state is a string and can contain any printable ASCII
TR

characters.
HA

The population of the city, district, or state is an integer and can be any positive
S
AK

integer.

The number of cities in a district is an integer and can be any positive integer.

The number of districts in Tamil Nadu is an integer and can be any positive integer.

Completion Status: Completed

Concepts Included:
gu - inheritance and exception handling: unit 2

Language Used: PYTHON 3

Source Code:
class City():
def __init__(self, name, population):
#..... YOUR CODE STARTS HERE .....

self.name = name
self.population = population

#..... YOUR CODE ENDS HERE .....

def print_details(self):
#..... YOUR CODE STARTS HERE .....
print(f"City: {self.name}, Population: {self.population}")

#..... YOUR CODE ENDS HERE .....

class District(City):
def __init__(self, name, population, num_cities):
#..... YOUR CODE STARTS HERE .....

)
m
super().__init__(name, population)

.co
self.num_cities = num_cities ail
gm
@

#..... YOUR CODE ENDS HERE .....


73
8

def print_details(self):
raj

#..... YOUR CODE STARTS HERE .....


at
h

print(f"District: {self.name}, Population: {self.population}, Number of Cities:


ks

{self.num_cities}")
(a
AJ
TR

#..... YOUR CODE ENDS HERE .....


HA
S
AK

class TamilNadu(District):
def __init__(self, name, population, num_districts):
#..... YOUR CODE STARTS HERE .....

super().__init__(name, population, num_districts)

#..... YOUR CODE ENDS HERE .....

def print_details(self):
#..... YOUR CODE STARTS HERE .....

print(f"State: {self.name}, Population: {self.population}, Number of Districts:


{self.num_cities}")

#..... YOUR CODE ENDS HERE .....

def clean_input(value):
return str(value.strip())
def main():
city_name, city_population = map(clean_input, input().strip().split(","))
city = City(city_name, int(city_population))

district_name, district_population, num_cities = map(clean_input,


input().strip().split(","))
district = District(district_name, int(district_population), int(num_cities))

state_name, state_population, num_districts = map(clean_input,


input().strip().split(","))
state = TamilNadu(state_name, int(state_population), int(num_districts))

city.print_details()
district.print_details()
state.print_details()

if __name__ == "__main__":
main()

)
m
Compilation Details:
.co
ail
gm

TestCase1:
@
73

Input:
8
raj

< hidden >


hat
ks

Expected Output:
(a
AJ

< hidden >


TR

Output:
HA
S

City: Chennai, Population: 4681087


AK

District: Chennai District, Population: 7100000, Number of Cities: 1


State: Tamil Nadu, Population: 77841267, Number of Districts: 38

Compilation Status: Passed


Execution Time:
0.011s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
City: Coimbatore, Population: 2154944
District: Coimbatore District, Population: 3472578, Number of Cities: 1
State: Tamil Nadu, Population: 77841267, Number of Districts: 38

Compilation Status: Passed


Execution Time:
0.011s

45. Design a Python program for a bookstore that uses classes and
inheritance. The bookstore sells two types of items: books and
magazines. Both books and magazines have a title and a price.
However, a book also has an author, while a magazine has an issue
number. Create classes to represent both items and use inheritance
to avoid code duplication.
Write a method in each class to print the details of the book or magazine. Also, write

)
m
a method in each class to change the price of the book or magazine.

.co
ail
Sample Input:
gm
@

The Great Gatsby, F. Scott Fitzgerald, 15.99Time, 5.99, 2312.994.99


738
raj

Sample Output:
at
h
ks

Book: The Great Gatsby by F. Scott Fitzgerald, priced at $15.99Magazine: Time, Issue
(a

No. 23, priced at $5.99Book: The Great Gatsby by F. Scott Fitzgerald, priced at
AJ

$12.99Magazine: Time, Issue No. 23, priced at $4.99


TR

Explanation:
SHA

In the sample output, each line represents the details of an item in the bookstore:
AK

The first line is the details of a book. It's "The Great Gatsby" by F. Scott Fitzgerald,
priced at $15.99.

The second line is the details of a magazine. It's "Time", Issue No. 23, priced at $5.99.

The third line is the updated details of the book after changing the price. The price of
"The Great Gatsby" has been updated to $12.99.

The fourth line is the updated details of the magazine after changing the price. The
price of "Time", Issue No. 23, has been updated to $4.99.

These details are printed by calling the print_details() method of each item object.
The method is defined in each class and prints the details specific to that item.

This is an example of single level inheritance, where the Book and Magazine classes
inherit from a common base class (Item). The base class defines properties and
methods common to all items (like name and price), while the derived classes add
properties and methods specific to books and magazines (like author and issue
number).

The change_price() method in each class demonstrates the concept of reusability in


object-oriented programming. Instead of writing separate functions to change the
price of a book and a magazine, we write a single method in the base class (Item)
that both Book and Magazine inherit. This allows us to change the price of any item,
regardless of whether it's a book or a magazine.

Constraints:

The title of the book or magazine is a string and can contain any printable ASCII
characters.

The author of the book is a string and can contain any printable ASCII characters.

The issue number of the magazine is an integer and can be any positive integer.

The price of the book or magazine is a float and can be any positive number.

)
m
Completion Status: Completed
.co
ail
Concepts Included:
gm
@

gu - inheritance and exception handling: unit 2


738
raj

Language Used: PYTHON 3


at
h
ks
(a

Source Code:
AJ
TR

class Item:
HA

def __init__(self, title, price):


S
AK

#..... YOUR CODE STARTS HERE .....


self.title = title
self.price = float(price)

#..... YOUR CODE ENDS HERE .....

def change_price(self, new_price):


#..... YOUR CODE STARTS HERE .....
self.price = float(new_price)

#..... YOUR CODE ENDS HERE .....

def print_details(self):
#..... YOUR CODE STARTS HERE .....

pass

#..... YOUR CODE ENDS HERE .....


class Book(Item):
def __init__(self, title, author, price):
#..... YOUR CODE STARTS HERE .....
super().__init__(title, price)
self.author = author

#..... YOUR CODE ENDS HERE .....

def print_details(self):
#..... YOUR CODE STARTS HERE .....
print(f"Book: {self.title} by {self.author}, priced at ${self.price:.2f}")

#..... YOUR CODE ENDS HERE .....

class Magazine(Item):

)
m
def __init__(self, title, price, issue):

.co
#..... YOUR CODE STARTS HERE ..... ail
super().__init__(title, price)
gm

self.issue = int(issue)
@
738

#..... YOUR CODE ENDS HERE .....


raj
hat

def print_details(self):
ks

#..... YOUR CODE STARTS HERE .....


(a

print(f"Magazine: {self.title}, Issue No. {self.issue}, priced at ${self.price:.2f}")


AJ
TR
HA

#..... YOUR CODE ENDS HERE .....


S
AK

def clean_input(ip):
return str(ip.strip())

book_title, book_author, book_price = map(clean_input, input().strip().split(","))


mz_title, mz_price, mz_issue = map(clean_input, input().strip().split(","))

book1 = Book(book_title, book_author, book_price)


magazine1 = Magazine(mz_title, mz_price, mz_issue)

# Printing initial details


book1.print_details()
magazine1.print_details()

# Changing prices
book1.change_price(input())
magazine1.change_price(input())

# Printing updated details


book1.print_details()
magazine1.print_details()

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Book: To Kill a Mockingbird by Harper Lee, priced at $10.99
Magazine: National Geographic, Issue No. 144, priced at $6.99
Book: To Kill a Mockingbird by Harper Lee, priced at $9.99

)
m
Magazine: National Geographic, Issue No. 144, priced at $5.99

.co
ail
Compilation Status: Passed
gm

Execution Time:
@
73

0.012s
8
raj
hat

TestCase2:
ks
(a

Input:
AJ
TR

< hidden >


HA

Expected Output:
S
AK

< hidden >

Output:
Book: 1984 by George Orwell, priced at $8.99
Magazine: Forbes, Issue No. 102, priced at $7.99
Book: 1984 by George Orwell, priced at $7.99
Magazine: Forbes, Issue No. 102, priced at $6.99

Compilation Status: Passed


Execution Time:
0.012s

46. Design a Python program for an e-commerce platform that sells


products. Each product on the platform has a name, price, and
seller. There are two types of products: new and used. Used
products have an additional attribute: condition.
Create classes to represent a Product, NewProduct, and UsedProduct. Use
inheritance and the super() function to avoid code duplication. Write a method in
each class to print the details of the product.

Sample Input:
Laptop, 1200.99, ElectronicsHubSmartphone, 450.50, TechResell, Good

Sample Output:
New Product: Laptop, Price: $1200.99, Seller: ElectronicsHubUsed Product:
Smartphone, Price: $450.50, Seller: TechResell, Condition: Good

Explanation:

In the sample output, each line represents the details of a product:

)
The first line is the details of a new product. It's a Laptop with a price of $1200.99

m
sold by ElectronicsHub.
.co
ail
The second line is the details of a used product. It's a Smartphone with a price of
gm

$450.50 sold by TechResell and its condition is Good.


@
73

These details are printed by calling the print_details() method of each product object.
8
raj

The method is defined in each class and prints the details specific to that product.
hat
ks

This is an example of single level inheritance, where the NewProduct and


(a

UsedProduct classes inherit from a common base class (Product). The base class
AJ

defines properties and methods common to all products (like name, price, and seller),
TR

while the derived classes add properties and methods specific to new and used
products. The super() function is used to call a method in the parent class from the
HA

child class.
S
AK

Constraints:

The name of the product and the seller is a string and can contain any printable ASCII
characters.

The price of the product is a float and can be any positive number.

The condition of the used product is a string and can contain any printable ASCII
characters.

Completion Status: Completed

Concepts Included:
gu - inheritance and exception handling: unit 2
Language Used: PYTHON 3

Source Code:

class Product:
def __init__(self, name, price, seller):
#..... YOUR CODE STARTS HERE .....
self.name = name
self.price = float(price)
self.seller = seller

#..... YOUR CODE ENDS HERE .....

def print_details(self):
#..... YOUR CODE STARTS HERE .....

pass

)
m
.co
#..... YOUR CODE ENDS HERE .....
ail
class NewProduct(Product):
gm

def print_details(self):
@

#..... YOUR CODE STARTS HERE .....


73

return f"New Product: {self.name}, Price: ${self.price:.2f}, Seller: {self.seller}"


8
raj
h at
ks

#..... YOUR CODE ENDS HERE .....


(a
AJ

class UsedProduct(Product):
TR

def __init__(self, name, price, seller, condition):


HA

#..... YOUR CODE STARTS HERE .....


super().__init__(name, price, seller)
S
AK

self.condition = condition

#..... YOUR CODE ENDS HERE .....

def print_details(self):
#..... YOUR CODE STARTS HERE .....
return f"Used Product: {self.name}, Price: ${self.price:.2f}, Seller: {self.seller},
Condition: {self.condition}"

#..... YOUR CODE ENDS HERE .....

# Get input from the user


product1_info = input().split(", ")
product2_info = input().split(", ")

# Create product objects


product1 = NewProduct(*product1_info)
if len(product2_info) == 4:
product2 = UsedProduct(*product2_info)
else:
product2 = None

# Print details
print(product1.print_details())
if product2:
print(product2.print_details())

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:

)
m
< hidden >
.co
ail
Output:
gm
@

New Product: Laptop, Price: $1200.99, Seller: ElectronicsHub


73

Used Product: Smartphone, Price: $450.50, Seller: TechResell, Condition: Good


8
raj

Compilation Status: Passed


h at
ks

Execution Time:
(a
AJ

0.016s
TR
HA

TestCase2:
S
AK

Input:
< hidden >

Expected Output:
< hidden >

Output:
New Product: Camera, Price: $699.99, Seller: CameraStore
Used Product: Tablet, Price: $299.99, Seller: Gadgets4Less, Condition: Fair

Compilation Status: Passed


Execution Time:
0.012s
47. You are developing a Python program for managing various
shapes in a geometry application. The program should support
different types of shapes, such as circles, rectangles, and triangles.
Each shape has its own unique attributes and methods.
Write a Python script that demonstrates method overloading in the context of
different shape classes. Your program should accomplish the following tasks:

Define a base class called Shape.

Implement different subclasses for various shapes, such as Circle, Rectangle, and
Triangle.

Each shape class should have methods to calculate its area and perimeter.

Demonstrate method overloading by implementing different versions of the area and


perimeter methods for each shape class.

Ensure the following operations can be performed:

)
m
.co
Calculate the area and perimeter of a circle. ail
gm

Calculate the area and perimeter of a rectangle.


@

Calculate the area and perimeter of a triangle.


738
raj

Your program should continuously prompt the user for shape inputs until the "quit"
h at

command is entered.
ks
(a

Provide appropriate error handling for invalid inputs. Display a message in the
AJ

following format for invalid inputs: "Invalid input. Please enter a valid shape (circle/
TR

rectangle/triangle)."
SHA
AK

Sample Input:
circle5rectangle4 6triangle3 4 5quit

Sample Output:
Area of the circle: 78.54Perimeter of the circle: 31.42Area of the rectangle:
24.0Perimeter of the rectangle: 20.0Area of the triangle: 6.0Perimeter of the triangle:
12.0Quitting the program.

Explanation:

The user selects a shape and provides the necessary dimensions.

The program calculates the area and perimeter based on the provided inputs and
shape type.

The process continues until the user enters "quit." If the user enters an invalid shape,
an appropriate error message is displayed.
Completion Status: Completed

Concepts Included:
gu - inheritance and exception handling: unit 2

Language Used: PYTHON 3

Source Code:

import math

class Shape:
#..... YOUR CODE STARTS HERE .....
def area(self, *args):
pass

def perimeter(self, *args):

)
m
pass
.co
ail
gm

#..... YOUR CODE ENDS HERE .....


@
73

class Circle(Shape):
8
raj

#..... YOUR CODE STARTS HERE .....


hat
ks

def area(self, radius):


(a

return math.pi * radius ** 2


AJ
TR

def perimeter(self, radius):


return 2 * math.pi * radius
HA
S
AK

#..... YOUR CODE ENDS HERE .....

class Rectangle(Shape):
#..... YOUR CODE STARTS HERE .....
def area(self, length, width):
return length * width

def perimeter(self, length, width):


return 2 * (length + width)

#..... YOUR CODE ENDS HERE .....

class Triangle(Shape):
#..... YOUR CODE STARTS HERE .....
def area(self, side1, side2, side3):
s = (side1 + side2 + side3) / 2
return math.sqrt(s * (s - side1) * (s - side2) * (s - side3))
def perimeter(self, side1, side2, side3):
return side1 + side2 + side3

#..... YOUR CODE ENDS HERE .....

def main():
shape_classes = {'circle': Circle(), 'rectangle': Rectangle(), 'triangle': Triangle()}
while True:
shape = input().lower()
if shape == 'quit':
print("Quitting the program.")
break
elif shape not in shape_classes:
print("Invalid input. Please enter a valid shape (circle/rectangle/triangle).")
continue

dimensions = list(map(float, input().split()))


print("Area of the {}: {:.2f}".format(shape, shape_classes[shape].area(*dimensions)))
print("Perimeter of the {}: {:.2f}".format(shape,

)
m
shape_classes[shape].perimeter(*dimensions)))

.co
ail
if __name__ == "__main__":
gm

main()
@
73

Compilation Details:
8
raj
at
h

TestCase1:
ks
(a

Input:
AJ
TR

< hidden >


HA

Expected Output:
S
AK

< hidden >

Output:
Area of the circle: 78.54
Perimeter of the circle: 31.42
Area of the rectangle: 24.00
Perimeter of the rectangle: 20.00
Area of the triangle: 6.00
Perimeter of the triangle: 12.00
Quitting the program.

Compilation Status: Passed


Execution Time:
0.012s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Area of the circle: 153.94
Perimeter of the circle: 43.98
Area of the rectangle: 15.00
Perimeter of the rectangle: 16.00
Area of the triangle: 24.00
Perimeter of the triangle: 24.00
Quitting the program.

Compilation Status: Passed


Execution Time:

)
m
.co
0.012s
ail
gm

48. You are tasked with creating a Python program to manage the
@
73

borrowing of resources from a library. The library offers both books


8
raj

and DVDs. Write a Python script that allows users to borrow items
at

from the library. Faculty members can only borrow DVDs, while
h
ks

students can borrow both books and DVDs.


(a
AJ

Here are the operations the program should support:


TR
HA

Allow a user to borrow an item from the library.


S
AK

Display a message indicating whether the borrowing was successful or not, based on
the user's status and the type of item they are trying to borrow.

Quit the program.

Ensure the following message formats:

For borrowing a book: Book "{book_title}" successfully borrowed by {self.name}.

For borrowing a DVD by a faculty member: DVD "{title}" successfully borrowed by


{self.name}.

For informing a faculty member that they can only borrow DVDs: Faculty members
can only borrow DVDs.

Please enter the following details for borrowing:

Name of the borrower


Status of the borrower (faculty/student)

Title of the item to borrow

Sample Input:
AlicefacultyThe Great Gatsbyquit

Sample Output:
Faculty members can only borrow DVDs.Quitting the program.

Explanation:

Alice, a faculty member, attempts to borrow "The Great Gatsby", which is a book.
However, the program informs her that faculty members can only borrow DVDs. Then,
the program quits as Alice does not attempt any further operations.

Please ensure to include "DVD" in the title if you want to borrow a DVD, as shown in
the sample input.

)
m
.co
ail
Completion Status: Completed
gm
@
73

Concepts Included:
8
raj

gu - inheritance and exception handling: unit 2


hat
ks
(a

Language Used: PYTHON 3


AJ
TR

Source Code:
SHA
AK

class User:
def __init__(self, name, user_type):
#..... YOUR CODE STARTS HERE .....
self.name = name
self.user_type = user_type

#..... YOUR CODE ENDS HERE .....

def borrow_book(self, book_title):


#..... YOUR CODE STARTS HERE .....
return f'Book "{book_title}" successfully borrowed by {self.name}.'

def borrow_dvd(self, dvd_title):


return f'DVD "{dvd_title}" successfully borrowed by {self.name}.'

#..... YOUR CODE ENDS HERE .....

class Faculty(User):
def __init__(self, name):
#..... YOUR CODE STARTS HERE .....
super().__init__(name, "faculty")

#..... YOUR CODE ENDS HERE .....

def borrow_book(self, title):


#..... YOUR CODE STARTS HERE .....
return "Faculty members can only borrow DVDs."

#..... YOUR CODE ENDS HERE .....

def main():
while True:
name = input()
user_type = input().lower()
if user_type == "faculty":
user = Faculty(name)

)
m
else:

.co
user = User(name, user_type) ail
gm

item_title = input()
@

if user_type == "faculty":
73

if "DVD" in item_title:
8

print(user.borrow_book(item_title))
raj

else:
h at

print("Faculty members can only borrow DVDs.")


ks

else:
(a

print(user.borrow_book(item_title))
AJ
TR

choice = input().lower()
HA

if choice != "yes":
S

print("Quitting the program.")


AK

break

if __name__ == "__main__":
main()

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Faculty members can only borrow DVDs.
Quitting the program.

Compilation Status: Passed


Execution Time:
0.015s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:

)
m
Book "The Lord of the Rings: The Fellowship of the Ring" successfully borrowed by

.co
David. ail
Quitting the program.
gm

Compilation Status: Passed


@
73

Execution Time:
8
raj
at

0.011s
h
ks
(a
AJ

49. You're developing a Python program for a virtual pet simulation


TR

game. The game features various types of pets, each with its own
HA

unique abilities and needs. You need to implement a system to


S
AK

manage different types of pets and their actions. The program


should support pets such as cats, dogs, and birds.
Write a Python script that demonstrates method overloading in the context of
different pet classes. Your program should accomplish the following tasks:

Define a base class called Pet.

Implement different subclasses for various types of pets, such as Cat, Dog, and Bird.

Each pet class should have methods to perform actions such as eating, sleeping, and
making sounds.

Demonstrate method overloading by implementing different versions of the eat(),


sleep(), and make_sound() methods for each pet class.

Additionally, integrate some unique behaviors for each type of pet:

Cats should be able to purr when making a sound.


Dogs should be able to wag their tails when making a sound.

Birds should be able to chirp when making a sound.

Ensure the following operations can be performed:

Feed a pet and display a message indicating it's eating.

Put a pet to sleep and display a message indicating it's sleeping.

Prompt a pet to make a sound and display the appropriate message based on its
type.

Your program should continuously prompt the user for pet actions until the "quit"
command is entered.

Provide appropriate error handling for invalid inputs. Display a message in the
following format for invalid inputs: "Invalid input. Please enter a valid action (feed/
sleep/make_sound/quit)."

)
m
.co
Sample Input:
ail
cateatdogmake_soundbirdsleepquit
gm
@
73

Sample Output:
8
raj

Cat is eating.Dog is wagging its tail.Bird is sleeping.Quitting the program.


hat
ks

Explanation:
(a
AJ

The user selects a pet and an action to perform.


TR
HA

The program executes the action based on the selected pet type and displays an
appropriate message.
S
AK

The process continues until the user enters "quit." If the user enters an invalid action,
an appropriate error message is displayed.

Completion Status: Completed

Concepts Included:
gu - inheritance and exception handling: unit 2

Language Used: PYTHON 3

Source Code:

class Pet:
#..... YOUR CODE STARTS HERE .....

def eat(self):
pass

def sleep(self):
pass

def make_sound(self):
pass

#..... YOUR CODE ENDS HERE .....

class Cat(Pet):
#..... YOUR CODE STARTS HERE .....
def eat(self):
print("Cat is eating.")

def sleep(self):

)
m
print("Cat is sleeping.")

.co
ail
def make_sound(self):
gm

print("Cat is purring.")
@
738

#..... YOUR CODE ENDS HERE .....


raj
h at

class Dog(Pet):
ks

#..... YOUR CODE STARTS HERE .....


(a

def eat(self):
AJ

print("Dog is eating.")
TR
HA

def sleep(self):
S

print("Dog is sleeping.")
AK

def make_sound(self):
print("Dog is wagging its tail.")

#..... YOUR CODE ENDS HERE .....

class Bird(Pet):
#..... YOUR CODE STARTS HERE .....
def eat(self):
print("Bird is eating.")

def sleep(self):
print("Bird is sleeping.")

def make_sound(self):
print("Bird is chirping.")
#..... YOUR CODE ENDS HERE .....

def main():
while True:
pet_type = input("").lower()
if pet_type == 'quit':
print("Quitting the program.")
break
elif pet_type not in ['cat', 'dog', 'bird']:
print("Invalid input. Please enter a valid pet type (cat/dog/bird).")
continue

pet_action = input("").lower()
if pet_action == 'quit':
print("Quitting the program.")
break
elif pet_action not in ['eat', 'sleep', 'make_sound']:
print("Invalid input. Please enter a valid action (eat/sleep/make_sound/quit).")
continue

)
m
if pet_type == 'cat':

.co
cat = Cat() ail
if pet_action == 'eat':
gm

cat.eat() # Output: "Cat is eating."


@

elif pet_action == 'sleep':


73

cat.sleep() # Output: "Cat is sleeping."


8

elif pet_action == 'make_sound':


raj

cat.make_sound() # Output: "Cat is purring."


at
h

elif pet_type == 'dog':


ks

dog = Dog()
(a

if pet_action == 'eat':
AJ

dog.eat() # Output: "Dog is eating."


TR

elif pet_action == 'sleep':


HA

dog.sleep() # Output: "Dog is sleeping."


S

elif pet_action == 'make_sound':


AK

dog.make_sound() # Output: "Dog is wagging its tail."


elif pet_type == 'bird':
bird = Bird()
if pet_action == 'eat':
bird.eat() # Output: "Bird is eating."
elif pet_action == 'sleep':
bird.sleep() # Output: "Bird is sleeping."
elif pet_action == 'make_sound':
bird.make_sound() # Output: "Bird is chirping."

if __name__ == "__main__":
main()

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Cat is eating.
Dog is wagging its tail.
Bird is sleeping.
Quitting the program.

Compilation Status: Passed


Execution Time:
0.012s

TestCase2:

)
m
Input:
.co
ail
< hidden >
gm

Expected Output:
@
73

< hidden >


8
raj
at

Output:
h
ks

Dog is eating.
(a

Bird is sleeping.
AJ

Quitting the program.


TR
HA

Compilation Status: Passed


S
AK

Execution Time:
0.012s

50. You are a college professor and you have two lists: one with the
names of your students and another with their corresponding
scores. You want to associate each student with their score. Write a
Python function associate_students(names, scores) that takes a list
of names and a list of scores and returns a list of tuples where each
tuple contains a name and the corresponding score. Use the zip
function to associate the names with the scores.

Input:

names: a list of strings representing the names of the students.


scores: a list of integers representing the scores of the students.

Output:

The function should return a list of tuples where each tuple contains a name and the
corresponding score.

Sample Input:
['Alice', 'Bob', 'Charlie', 'Dave'], [85, 90, 78, 92]

Sample Output:
[('Alice', 85), ('Bob', 90), ('Charlie', 78), ('Dave', 92)]

Explanation:

)
The zip function takes two or more iterable objects (like lists or strings), aggregates

m
them in a tuple, and returns it. In this case, it takes a name from the names list and a
.co
score from the scores list and puts them together in a tuple. This demonstrates how
ail
the zip function can be used to combine two lists into a list of tuples. In the context of
gm

grading students in a college, this can be useful to associate each student with their
@

score.
73
8
raj
at

Completion Status: Completed


h
ks
(a
AJ

Concepts Included:
TR

gu - functional programming: unit 3


SHA
AK

Language Used: PYTHON 3

Source Code:
import re

def associate_students(names, scores):


#..... YOUR CODE STARTS HERE .....

return list(zip(names, scores))

#..... YOUR CODE ENDS HERE .....

def clean_input(value):
value = value.strip()
return re.sub(r'[^A-Z0-9a-z,]', '', value).split(',')

if __name__ == "__main__":
names, scores = list(map(clean_input, input().strip().split('],')))
scores = list(map(int, scores))
print(associate_students(names, scores))

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
[('Alice', 85), ('Bob', 90), ('Charlie', 78), ('Dave', 92)]

Compilation Status: Passed

)
m
.co
Execution Time:
ail
0.017s
gm
@
73

TestCase2:
8
raj

Input:
at
h
ks

< hidden >


(a
AJ

Expected Output:
TR

< hidden >


SHA

Output:
AK

[('Eve', 88), ('Frank', 92), ('Grace', 95), ('Heidi', 90)]

Compilation Status: Passed


Execution Time:
0.026s

51. You are a college professor and you have the scores of your
students in a list. You want to find the total score of all students.
Write a Python function total_score(scores) that takes a list of
scores and returns the total score. Use the reduce function to
calculate the total score.

Input:
scores: a list of integers representing the scores of the students.

Output:

The function should return an integer representing the total score of all students.

Sample Input:
[85, 90, 78, 92]

Sample Output:
345

Explanation:

The reduce function applies a function of two arguments cumulatively to the items of

)
an iterable, from left to right, so as to reduce the iterable to a single output. In this

m
case, it takes two scores at a time and adds them, continuing this process until all
.co
scores have been added together. This demonstrates how the reduce function can be
ail
used to reduce a list to a single result. In the context of grading students in a college,
gm

this can be useful to calculate the total score of all students.


@
738
raj

Completion Status: Completed


hat
ks
(a

Concepts Included:
AJ

gu - functional programming: unit 3


TR
HA

Language Used: PYTHON 3


S
AK

Source Code:
import json
from io import StringIO
from functools import reduce

def total_score(scores):
#..... YOUR CODE STARTS HERE .....

return reduce(lambda x, y: x + y, scores)

#..... YOUR CODE ENDS HERE .....

def clean_input(value):
return json.load(StringIO(value))

if __name__ == "__main__":
scores = clean_input(input().strip())
print(total_score(scores))

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
345

Compilation Status: Passed

)
m
.co
Execution Time:
ail
0.018s
gm
@
73

TestCase2:
8
raj

Input:
h at
ks

< hidden >


(a
AJ

Expected Output:
TR

< hidden >


HA
S

Output:
AK

365

Compilation Status: Passed


Execution Time:
0.024s

52. You are given a string that represents a list of movies and their
release years. The format of the string is "<movie title> (<release
year>)". Write a Python function get_movies(data) that takes this
string and returns a list of tuples where each tuple contains the
movie title and the release year. Use regular expressions to parse
the data.
Input:

data: a string representing a list of movies and their release years.

Output:

The function should return a list of tuples where each tuple contains a movie title and
the release year.

Sample Input:
The Shawshank Redemption (1994), The Godfather (1972), The Dark Knight (2008)

Sample Output:
[('The Shawshank Redemption', '1994'), ('The Godfather', '1972'), ('The Dark Knight',

)
'2008')]

m
Explanation:
.co
ail
gm

The re.findall function applies the regular expression pattern to the data string and
@

returns a list of tuples where each tuple contains the movie title and the release year.
738
raj
at

Completion Status: Completed


h
ks
(a

Concepts Included:
AJ
TR

gu - functional programming: unit 3


SHA

Language Used: PYTHON 3


AK

Source Code:
import re

def get_movies(data):
#..... YOUR CODE STARTS HERE .....

# Define the regular expression pattern


pattern = r'([\w\s]+) \((\d{4})\)'

# Find all matches using the pattern


matches = re.findall(pattern, data)

# Create a list of tuples from the matches


movies = [(title.strip(), year) for title, year in matches]

return movies
#..... YOUR CODE ENDS HERE .....

if __name__ == "__main__":
data = input().strip()
print(get_movies(data))

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:

)
m
.co
[('The Shawshank Redemption', '1994'), ('The Godfather', '1972'), ('The Dark Knight',
ail
'2008')]
gm

Compilation Status: Passed


@
73

Execution Time:
8
raj
at

0.018s
h
ks
(a

TestCase2:
AJ
TR

Input:
HA
S

< hidden >


AK

Expected Output:
< hidden >

Output:
[('Pulp Fiction', '1994'), ('Fight Club', '1999'), ('Forrest Gump', '1994')]

Compilation Status: Passed


Execution Time:
0.017s

53. You are implementing a simple calculator. Write a Python class


Calculator with static methods add, subtract, multiply, and divide
that perform the respective operations.
Input:

num1: a float, the first number.

num2: a float, the second number.

Output:

The function should return the result of the operation.

Sample Input:
Calculator.add(5, 3)

Sample Output:
8

)
m
.co
Explanation: ail
gm

The class Calculator has static methods add, subtract, multiply, and divide which
perform the respective operations. Static methods, marked with the @staticmethod
@
73

decorator, don't take a self or cls parameter. This means you can't modify object state
8

or class state within a static method. However, they're useful when you need to
raj

perform a utility function that doesn't modify the state of the object or class, like in
at

this case where we're performing simple mathematical operations.


h
ks
(a
AJ

Completion Status: Completed


TR
HA

Concepts Included:
S
AK

gu - functional programming: unit 3

Language Used: PYTHON 3

Source Code:
class Calculator:
@staticmethod
def add(num1, num2):
#..... YOUR CODE STARTS HERE .....

return num1 + num2

#..... YOUR CODE ENDS HERE .....

@staticmethod
def subtract(num1, num2):
#..... YOUR CODE STARTS HERE .....

return num1 - num2

#..... YOUR CODE ENDS HERE .....

@staticmethod
def multiply(num1, num2):
#..... YOUR CODE STARTS HERE .....

return num1 * num2

#..... YOUR CODE ENDS HERE .....

@staticmethod
def divide(num1, num2):
#..... YOUR CODE STARTS HERE .....

if num2 != 0:
return num1 / num2

)
m
else:

.co
raise ValueError("Cannot divide by zero") ail
gm

#..... YOUR CODE ENDS HERE .....


@
73

def call_func(func, args):


8

value = None
raj

num1, num2 = args


at
h
ks

if (func == "add"):
(a

value = Calculator.add(num1, num2)


AJ
TR

elif (func == "subtract"):


HA

value = Calculator.subtract(num1, num2)


S
AK

elif (func == "multiply"):


value = Calculator.multiply(num1, num2)

elif (func == "divide"):


value = Calculator.divide(num1, num2)

return value

if __name__ == "__main__":
func_call = list(map(lambda x: str(x.strip()), input().strip().split('.')))
class_name, func = func_call

if (class_name == 'Calculator'):
parans_pos = func.index('(')

name = func[:parans_pos].strip()
args = tuple(map(lambda x: int(x.strip()), func[parans_pos+1:
len(func)-1].strip().split(',')))
print(call_func(name, args))

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
8

Compilation Status: Passed

)
m
.co
Execution Time:
ail
0.012s
gm
@
73

TestCase2:
8
raj

Input:
h at
ks

< hidden >


(a
AJ

Expected Output:
TR

< hidden >


HA
S

Output:
AK

Compilation Status: Passed


Execution Time:
0.012s

54. You are a college professor and you have the scores of your
students in a list. You want to find out which students have passed
the course. A student passes the course if they score 60 or more.
Write a Python function passed_students(scores) that takes a list of
scores and returns a list of scores that are 60 or more. Use the filter
function to filter out the passing scores.
Input:

scores: a list of integers representing the scores of the students.

Output:

The function should return a list of integers representing the scores of the students
who have passed.

Sample Input:
[55, 60, 65, 70, 75, 80, 85, 90, 95, 100]

Sample Output:
[60, 65, 70, 75, 80, 85, 90, 95, 100]

)
m
Explanation:
.co
ail
The filter function applies a function to every item in the scores list and returns a new
gm

list with the items for which the function returns True. In this case, the function is a
@

lambda function that checks if a score is 60 or more. This demonstrates how the
73

filter function can be used to filter items in a list based on a condition. In the context
8

of grading students in a college, this can be useful to find out which students have
raj
at

passed the course based on their scores.


h
ks
(a
AJ

Completion Status: Completed


TR
HA

Concepts Included:
S
AK

gu - functional programming: unit 3

Language Used: PYTHON 3

Source Code:
import json
from io import StringIO

def passed_students(scores):
#..... YOUR CODE STARTS HERE .....

return list(filter(lambda x: x >= 60, scores))

#..... YOUR CODE ENDS HERE .....

if __name__ == "__main__":
scores = json.load(StringIO(input().strip()))
passed_students = passed_students(scores)

print(passed_students)

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
[60, 65, 70, 75, 80, 85, 90, 95, 100]

)
Compilation Status: Passed

m
Execution Time: .co
ail
gm

0.019s
@
738

TestCase2:
raj
at

Input:
h
ks
(a

< hidden >


AJ
TR

Expected Output:
HA

< hidden >


S
AK

Output:
[60, 65, 70]

Compilation Status: Passed


Execution Time:
0.027s

55. You are managing an e-commerce website and you have a list
of products. Each product is represented as a dictionary with two
keys: 'name' and 'price'. You want to create a list of all products that
cost more than $50. Write a Python function
expensive_products(products) that takes a list of products and
returns a list of the names of products that cost more than $50. Use
a list comprehension to create the list.
Input:

products: a list of dictionaries. Each dictionary represents a product and has two
keys: 'name' (a string) and 'price' (a float).

Output:

The function should return a list of strings representing the names of products that
cost more than $50.

Sample Input:
[{'name': 'Product 1', 'price': 49.99}, {'name': 'Product 2', 'price': 50.01}, {'name': 'Product
3', 'price': 50.00}]

Sample Output:

)
m
.co
['Product 2']
ail
Explanation:
gm
@

The list comprehension generates a new list containing the names of all products
73

that cost more than $50. It does this by iterating over each product in the products
8

list and checking if the product's price is greater than $50. If it is, the product's name
raj
at

is added to the new list. This demonstrates how list comprehensions can be used to
h

create new lists based on existing lists in Python. In the context of managing an e-
ks

commerce website, this can be useful to quickly find all products that meet a certain
(a

price criterion.
AJ
TR
HA

Completion Status: Completed


S
AK

Concepts Included:
gu - functional programming: unit 3

Language Used: PYTHON 3

Source Code:
import json
from io import StringIO
import re

def expensive_products(products):
#..... YOUR CODE STARTS HERE .....

return [product['name'] for product in products if product['price'] > 50]


#..... YOUR CODE ENDS HERE .....

def convert_to_list_of_dicts(data):
data_without_brackets = re.sub(r'[\[\]]', '', data).split('},')

lst = []

data = [d + '}' if '}' not in d else d for d in data_without_brackets]

for d in data:
if ('{' in d and '}' in d):
d = d.strip().replace("'", '"')
lst.append(json.load(StringIO(d)))

return lst

if __name__ == "__main__":
products = convert_to_list_of_dicts(input().strip())
print(expensive_products(products))

)
m
Compilation Details:
.co
ail
gm

TestCase1:
@
73

Input:
8
raj

< hidden >


at
h
ks

Expected Output:
(a
AJ

< hidden >


TR

Output:
HA
S

['Product 2']
AK

Compilation Status: Passed


Execution Time:
0.019s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
['Product A', 'Product B']
Compilation Status: Passed
Execution Time:
0.019s

56. You are managing an e-commerce website and you have a list
of products. Each product is represented as a dictionary with two
keys: 'name' and 'category'. You want to create a list of all products
that belong to the category 'Electronics'. Write a Python function
electronics_products(products) that takes a list of products and
returns a list of tuples where each tuple contains the product name
and the category. Use a tuple comprehension to create the list.

Input:

)
products: a list of dictionaries. Each dictionary represents a product and has two

m
.co
keys: 'name' (a string) and 'category' (a string).
ail
gm

Output:
@
738
raj

The function should return a list of tuples where each tuple contains a product name
at

and the category.


h
ks
(a
AJ

Sample Input:
TR
HA

[{'name': 'Product 1', 'category': 'Books'}, {'name': 'Product 2', 'category': 'Electronics'},
{'name': 'Product 3', 'category': 'Electronics'}]
S
AK

Sample Output:
[('Product 2', 'Electronics'), ('Product 3', 'Electronics')]

Explanation:

The tuple comprehension generates a new list containing tuples of the names and
categories of all products that belong to the 'Electronics' category. It does this by
iterating over each product in the products list and checking if the product's category
is 'Electronics'. If it is, a tuple containing the product's name and category is added to
the new list. This demonstrates how tuple comprehensions can be used to create
new lists based on existing lists in Python. In the context of managing an e-
commerce website, this can be useful to quickly find all products that belong to a
certain category.

Completion Status: Completed


Concepts Included:
gu - functional programming: unit 3

Language Used: PYTHON 3

Source Code:
import json
from io import StringIO
import re

def electronics_products(products):
#..... YOUR CODE STARTS HERE .....

return [(product['name'], product['category']) for product in products if


product['category'] == 'Electronics']

#..... YOUR CODE ENDS HERE .....

)
m
.co
def convert_to_list_of_dicts(data): ail
data_without_brackets = re.sub(r'[\[\]]', '', data).split('},')
gm

lst = []
@
73
8

data = [d + '}' if '}' not in d else d for d in data_without_brackets]


raj
at

for d in data:
h
ks

if ('{' in d and '}' in d):


(a

d = d.strip().replace("'", '"')
AJ

lst.append(json.load(StringIO(d)))
TR
HA

return lst
S
AK

if __name__ == "__main__":
products = convert_to_list_of_dicts(input().strip())
print(electronics_products(products))

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
[('Product 2', 'Electronics'), ('Product 3', 'Electronics')]
Compilation Status: Passed
Execution Time:
0.019s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
[('iPhone 13', 'Electronics'), ('Samsung Galaxy S21', 'Electronics')]

Compilation Status: Passed

)
m
.co
Execution Time: ail
gm

0.019s
@
738

57. You are managing an e-commerce website and you have a list
raj

of products. Each product is represented as a dictionary with three


at
h

keys: 'name', 'category', and 'brand'. You want to create a set of all
ks
(a

unique brands present in your product list. Write a Python function


AJ

unique_brands(products) that takes a list of products and returns a


TR

set of unique brands. Use a set comprehension to create the set.


HA
S
AK

Input:

products: a list of dictionaries. Each dictionary represents a product and has three
keys: 'name' (a string), 'category' (a string), and 'brand' (a string).

Output:

The function should return a set of unique brands.

Sample Input:
[{'name': 'Product 1', 'category': 'Books', 'brand': 'Brand A'}, {'name': 'Product 2',
'category': 'Electronics', 'brand': 'Brand B'}, {'name': 'Product 3', 'category': 'Electronics',
'brand': 'Brand B'}]
Sample Output:
['Brand A', 'Brand B']

Explanation:

The set comprehension generates a new set containing unique brands of all
products. It does this by iterating over each product in the products list and adding
the product's brand to the new set. Since sets in Python only contain unique
elements, any duplicate brands are automatically removed. This demonstrates how
set comprehensions can be used to create new sets based on existing lists in Python.
In the context of managing an e-commerce website, this can be useful to quickly find
all unique product brands.",

Completion Status: Completed

Concepts Included:
gu - functional programming: unit 3

)
m
Language Used: PYTHON 3 .co
ail
gm
@

Source Code:
73
8

import json
raj

from io import StringIO


at
h

import re
ks
(a

def unique_brands(products):
AJ

#..... YOUR CODE STARTS HERE .....


TR
HA

return sorted({product['brand'] for product in products})


S
AK

#..... YOUR CODE ENDS HERE .....

def convert_to_list_of_dicts(data):
data_without_brackets = re.sub(r'[\[\]]', '', data).split('},')

lst = []

data = [d + '}' if '}' not in d else d for d in data_without_brackets]

for d in data:
if ('{' in d and '}' in d):
d = d.strip().replace("'", '"')
lst.append(json.load(StringIO(d)))

return lst

if __name__ == "__main__":
products = convert_to_list_of_dicts(input().strip())
print(sorted(unique_brands(products)))
Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
['Brand A', 'Brand B']

Compilation Status: Passed


Execution Time:
0.019s

)
m
TestCase2: .co
ail
gm

Input:
@
73

< hidden >


8
raj

Expected Output:
h at
ks

< hidden >


(a
AJ

Output:
TR

['Apple', 'Bloomsbury', 'Samsung']


SHA

Compilation Status: Passed


AK

Execution Time:
0.019s

58. You are managing an e-commerce website and you have a list
of products. Each product is represented as a dictionary with three
keys: 'name', 'category', and 'stock'. The 'stock' key represents the
number of units of the product available in your inventory. You want
to create a dictionary where the keys are the product names and the
values are the stock count. Write a Python function
product_stock(products) that takes a list of products and returns a
dictionary of product names and their stock count. Use a dictionary
comprehension to create the dictionary.
Input:

products: a list of dictionaries. Each dictionary represents a product and has three
keys: 'name' (a string), 'category' (a string), and 'stock' (an integer).

Output:

The function should return a dictionary where the keys are product names and the
values are their stock count.

Sample Input:
[{'name': 'Product 1', 'category': 'Books', 'stock': 20}, {'name': 'Product 2', 'category':
'Electronics', 'stock': 15}, {'name': 'Product 3', 'category': 'Electronics', 'stock': 30}]

Sample Output:

)
m
.co
{'Product 1': 20, 'Product 2': 15, 'Product 3': 30}
ail
Explanation:
gm
@

The dictionary comprehension generates a new dictionary containing product names


73

as keys and their stock count as values. It does this by iterating over each product in
8

the products list and adding an entry to the new dictionary where the key is the
raj
at

product's name and the value is the product's stock count. This demonstrates how
h

dictionary comprehensions can be used to create new dictionaries based on existing


ks

lists in Python. In the context of managing an e-commerce website, this can be useful
(a

to quickly find the stock count of a product given its name.


AJ
TR
HA

Completion Status: Completed


S
AK

Concepts Included:
gu - functional programming: unit 3

Language Used: PYTHON 3

Source Code:
def product_stock(products):
#..... YOUR CODE STARTS HERE .....

return {product['name']: product['stock'] for product in products}

#..... YOUR CODE ENDS HERE .....

products_input = eval(input())
result = product_stock(products_input)
print(result)

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
{'iPhone 13': 10, 'Harry Potter': 20, 'Samsung Galaxy S21': 15}

Compilation Status: Passed

)
m
.co
Execution Time:
ail
0.011s
gm
@
73

TestCase2:
8
raj

Input:
at
h
ks

< hidden >


(a
AJ

Expected Output:
TR

< hidden >


SHA

Output:
AK

{'MacBook Pro': 5, 'The Alchemist': 30, 'Dell XPS': 7}

Compilation Status: Passed


Execution Time:
0.011s

59. You are managing an e-commerce website and you have a list
of products. Each product is represented as a dictionary with three
keys: 'name', 'category', and 'price'. You want to calculate the total
price of all products in a specific category. Write a Python function
total_price(products, category) that takes a list of products and a
category, and returns the total price of all products in that category.
Use the sum function from the built-in Python math module to
calculate the total price.

Input:

products: a list of dictionaries. Each dictionary represents a product and has three
keys: 'name' (a string), 'category' (a string), and 'price' (a float).

category: a string representing the category of products for which the total price
should be calculated.

Output:

The function should return a float representing the total price of all products in the
specified category.

Sample Input:

)
m
.co
[{'name': 'Product 1', 'category': 'Books', 'price': 19.99}, {'name': 'Product 2', 'category':
ail
'Electronics', 'price': 299.99}, {'name': 'Product 3', 'category': 'Electronics', 'price':
gm

499.99}], 'Electronics'
@
73

Sample Output:
8
raj

799.98
hat
ks

Explanation:
(a
AJ

The generator expression generates a sequence of prices for all products in the
TR

specified category. It does this by iterating over each product in the products list and
HA

checking if the product's category matches the specified category. If it does, the
product's price is added to the sequence. The fsum function from the math module
S
AK

then calculates the sum of this sequence, which is the total price of all products in
the specified category. This demonstrates how modules and packages can be used in
Python to provide additional functionality, such as mathematical operations. In the
context of managing an e-commerce website, this can be useful to quickly calculate
the total price of all products in a certain category.

Completion Status: Completed

Concepts Included:
gu - functional programming: unit 3

Language Used: PYTHON 3

Source Code:
import json
from io import StringIO
import re
from math import fsum

def total_price(products, category):


#..... YOUR CODE STARTS HERE .....

return fsum(product['price'] for product in products if product['category'] == category)

#..... YOUR CODE ENDS HERE .....

def convert_to_list_of_dicts(data):
data_without_brackets = re.sub(r'[\[\]]', '', data).split('},')

lst = []

data = [d + '}' if '}' not in d else d for d in data_without_brackets]

for d in data:

)
m
if ('{' in d and '}' in d):

.co
d = d.strip().replace("'", '"') ail
lst.append(json.load(StringIO(d)))
gm
@

return lst
73
8

if __name__ == "__main__":
raj

ip = input().strip().replace("],", ']<DIVIDE>')
at
h

products, category = ip.split("<DIVIDE>")


ks

products = convert_to_list_of_dicts(products)
(a

category = category.replace("'", '').strip()


AJ
TR

print(total_price(products, category))
HA
S
AK

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
1799.98

Compilation Status: Passed


Execution Time:
0.019s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
2499.98

Compilation Status: Passed


Execution Time:
0.019s

)
m
.co
ail
60. You are managing a bank's software system. Every time a
gm

customer makes a transaction, the transaction amount is recorded.


@

You want to create a function that calculates the square root of the
738

transaction amount. Write a Python function


raj

transaction_sqrt(transaction_amount) that takes a transaction


at
h

amount and returns the square root of the transaction amount. Use
ks
(a

the sqrt function from the built-in Python math module to calculate
AJ

the square root.


TR
HA

Input:
S
AK

transaction_amount: a float representing the transaction amount.

Output:

The function should return a float representing the square root of the transaction
amount.

Sample Input:
100.0

Sample Output:
10.0
Explanation :

The sqrt function from the math module calculates the square root of a number. In
the context of managing a bank's software system, this can be useful to perform
various calculations related to the transaction amount.

Completion Status: Completed

Concepts Included:
gu - functional programming: unit 3

Language Used: PYTHON 3

Source Code:
from math import sqrt

)
m
def transaction_sqrt(transaction_amount):
.co
#..... YOUR CODE STARTS HERE ..... ail
gm

return sqrt(transaction_amount)
@
73

#..... YOUR CODE ENDS HERE .....


8
raj
at

transaction_amount = float(input())
h

result = transaction_sqrt(transaction_amount)
ks
(a

print(result)
AJ
TR

Compilation Details:
SHA
AK

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
10.0

Compilation Status: Passed


Execution Time:
0.011s
TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
7.0

Compilation Status: Passed


Execution Time:
0.015s

)
61. You are managing a bank's software system. You want to

m
.co
calculate the monthly interest for a given principal amount, rate of
ail
interest, and time period. Write a Python function
gm

calculate_interest(principal, rate, time) to calculate and return the


@

monthly interest.
738
raj
at

Input:
h
ks
(a

principal: a float representing the principal amount.


AJ
TR

rate: a float representing the annual rate of interest in percentage.


HA

time: an integer representing the time period in months.


S
AK

Output:

The function should return a float representing the monthly interest.

Sample Input:
1000.0, 5, 12

Sample Output:
50.0

Explanation:

The calculate_interest function takes three parameters: principal, rate, and time,
representing the principal amount, annual rate of interest (in percentage), and time
period (in months) respectively. Inside the function, it first converts the annual rate to
a monthly rate by dividing it by 100 and then by 12 (since there are 12 months in a
year).

Then, it calculates the monthly interest by multiplying the principal amount with the
monthly rate and the time period.

Completion Status: Completed

Concepts Included:
gu - functional programming: unit 3

Language Used: PYTHON 3

Source Code:

)
m
.co
def calculate_interest(principal, rate, time): ail
#..... YOUR CODE STARTS HERE .....
gm
@

monthly_rate = rate / (100 * 12) # Convert annual rate to monthly rate


73

monthly_interest = principal * monthly_rate * time


8

return monthly_interest
raj
at
h

#..... YOUR CODE ENDS HERE .....


ks
(a
AJ

if __name__ == "__main__":
TR

principal, rate, time = list(map(float, input().strip().split(',')))


HA
S

# Calculate and print monthly interest


AK

print(calculate_interest(principal, rate, time))

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
50.0

Compilation Status: Passed


Execution Time:
0.011s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
280.0

Compilation Status: Passed


Execution Time:

)
m
.co
0.011s
ail
gm
@

62. You are working on a Python project that involves performing


73

complex mathematical operations. For this project, you need to


8
raj

calculate the square root of a list of transaction amounts. So write a


at

Python function calculate_sqrt(transaction_amounts) that takes a


h
ks

list of transaction amounts and returns a list of their square roots.


(a
AJ
TR

Sample Input:
HA

[100.0, 200.0, 300.0, 400.0]


S
AK

Sample Output:
[10.0, 14.142135623730951, 17.320508075688775, 20.0]

Explanation:

The calculate_sqrt function uses the sqrt function from the math module to calculate
the square root of each transaction amount. The square root of a number is a value
that, when multiplied by itself, gives the original number. In this case, we're
calculating the square root of each transaction amount in the list.

Completion Status: Completed

Concepts Included:
gu - functional programming: unit 3
Language Used: PYTHON 3

Source Code:
import math

def calculate_sqrt(transaction_amounts):
#..... YOUR CODE STARTS HERE .....

return [math.sqrt(amount) for amount in transaction_amounts]

#..... YOUR CODE ENDS HERE .....

if __name__ == "__main__":
transaction_amounts = eval(input().strip())
print(calculate_sqrt(transaction_amounts))

Compilation Details:

)
m
.co
TestCase1:
ail
Input:
gm
@

< hidden >


73
8

Expected Output:
raj
at
h

< hidden >


ks
(a

Output:
AJ
TR

[10.0, 14.142135623730951, 17.320508075688775, 20.0]


HA

Compilation Status: Passed


S
AK

Execution Time:
0.011s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
[22.360679774997898, 24.49489742783178, 26.457513110645905,
28.284271247461902]

Compilation Status: Passed


Execution Time:
0.012s

63. You are a college professor and you have the scores of your
students in a list. You want to grade the students based on their
scores. Write a Python function grade_students(scores) that takes a
list of scores and returns a list of grades. Use the map function to
apply the grading scheme to all scores.
The grading scheme is as follows:

Score >= 90: 'A'

80 <= Score < 90: 'B'

70 <= Score < 80: 'C'

)
60 <= Score < 70: 'D'

m
.co
Score < 60: 'F' ail
gm
@

Input:
738
raj

scores: a list of integers representing the scores of the students.


hat
ks
(a

Output:
AJ
TR
HA

The function should return a list of strings representing the grades of the students.
S
AK

Sample Input:
[95,55]

Sample Output:
['A','F']

Explanation:

The map function applies the get_grade function to every item in the scores list. The
get_grade function takes a score and returns a grade based on the grading scheme.
This demonstrates how the map function can be used to apply a function to every
item in a list. In the context of grading students in a college, this can be useful to
grade all students based on their scores.

Completion Status: Completed


Concepts Included:
gu - functional programming: unit 3

Language Used: PYTHON 3

Source Code:
import json
from io import StringIO

def grade_students(scores):
def get_grade(score):
#..... YOUR CODE STARTS HERE .....

if score >= 90:


return 'A'
elif 80 <= score < 90:
return 'B'

)
m
elif 70 <= score < 80:

.co
return 'C' ail
elif 60 <= score < 70:
gm

return 'D'
else:
@
73

return 'F'
8
raj

#..... YOUR CODE ENDS HERE .....


at
h
ks

return list(map(get_grade, scores))


(a
AJ

if __name__ == "__main__":
TR

scores = json.load(StringIO(input().strip()))
HA

grades = grade_students(scores)
S
AK

print(grades)

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
['A', 'B', 'C', 'D', 'F']

Compilation Status: Passed


Execution Time:
0.019s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
['A', 'A', 'B', 'C', 'D']

Compilation Status: Passed


Execution Time:

)
m
.co
0.024s
ail
gm
@

64. In an e-commerce application, you have a list of n products.


73

Each product has a unique ID and a price. You need to implement a


8
raj

generator function get_products_in_budget(budget, products) that


at

yields products one by one, sorted by price, until the total price of
h
ks

yielded products exceeds the budget.


(a
AJ
TR

Input:
HA
S
AK

budget: an integer representing the total budget.

products: a list of tuples. Each tuple contains two elements - the first element is the
product ID (a string), and the second element is the product price (an integer).

Output:

The function should yield tuples. Each tuple contains two elements - the first element
is the product ID (a string), and the second element is the product price (an integer).

Constraints:

1 <= n <= 10^5

1 <= budget <= 10^9

1 <= price <= 10^6


Sample Input:
100[("p1", 30), ("p2", 50), ("p3", 40), ("p4", 60)]

Sample Output:
('p1', 30)('p3', 40)

Explanation:

The generator function get_products_in_budget yields products one by one, sorted by


price, until the total price of yielded products exceeds the budget. In this case, the
products "p1" and "p3" are yielded, with total price 30+40=70, which is the maximum
possible total price not exceeding the budget of 100.

This question highlights the importance and performance benefits of generators.


Generators allow us to generate as we go along, instead of holding everything in
memory. In the context of an e-commerce application, this can be particularly useful
when dealing with a large number of products, as it allows us to efficiently process
each product one at a time, reducing memory usage.

)
m
Completion Status: Completed .co
ail
gm
@

Concepts Included:
738

gu - functional programming: unit 3


raj
h at
ks

Language Used: PYTHON 3


(a
AJ

Source Code:
TR
HA

import re
S
AK

def get_products_in_budget(budget, products):


#..... YOUR CODE STARTS HERE .....

products.sort(key=lambda x: x[1])

total_price = 0

# Yield products one by one until total price exceeds budget


for product_id, price in products:
if total_price + price <= budget:
yield product_id, price
total_price += price
else:
break

#..... YOUR CODE ENDS HERE .....

def replace_non_alphanumeric(text, replacement=''):


return re.sub(r'[^a-zA-Z0-9,]', replacement, text)
def clean_input(value):
value = replace_non_alphanumeric(value).split(',')

id, price = list(map(lambda x: x.strip(), value))

return (id, int(price))

if __name__ == "__main__":
budget = int(input())
products = input()

products = list(map(clean_input, products.strip().replace('[', '').replace(']', '').split('),')))

for product in get_products_in_budget(budget, products):


print(product)

Compilation Details:

)
m
TestCase1:
.co
ail
Input:
gm

< hidden >


@
73

Expected Output:
8
raj
at

< hidden >


h
ks

Output:
(a
AJ

('p1', 30)
TR

('p3', 40)
HA
S

Compilation Status: Passed


AK

Execution Time:
0.017s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
('p1', 10)
('p2', 20)
Compilation Status: Passed
Execution Time:
0.022s

65. You are organizing a marriage function and you have a list of
tasks to be done. Each task has a time duration. You want to keep
track of how long each task takes. Write a Python decorator time_it
that takes a function and prints the time taken by that function. Use
this decorator to decorate the function do_task(task), which
simulates doing the task by sleeping for the duration of the task.
The output of the do_task function should be in the format: f"{task[0]} took
{round(end - start, 2)} seconds"

Input:

)
m
.co
task: a tuple. The first element is the task name (a string), and the second element is
ail
the task duration in seconds (an integer).
gm
@
73

Output:
8
raj
hat

The function should print the task name and the time taken by the task in the format:
ks

f"{task[0]} took {round(end - start, 2)} seconds"


(a
AJ
TR

Sample Input:
SHA

Decorating the hall, 2


AK

Sample Output:
Decorating the hall took 2.0 seconds

Explanation:

The decorator time_it is used to measure the time taken by the function do_task. The
do_task function simulates doing a task by sleeping for the duration of the task. The
decorator prints the task name and the time taken by the task. This demonstrates
how decorators can be used to modify the behavior of a function, in this case, by
adding timing functionality. In the context of organizing a marriage function, this can
be useful to keep track of how long each task takes.

Completion Status: Completed

Concepts Included:
gu - functional programming: unit 3

Language Used: PYTHON 3

Source Code:
import time

def time_it(func):
#..... YOUR CODE STARTS HERE .....

def wrapper(task):
start_time = time.time()
result = func(task)
end_time = time.time()
duration = end_time - start_time
print(f"{task[0]} took {round(duration, 2)} seconds")
return result
return wrapper

)
m
.co
#..... YOUR CODE ENDS HERE ..... ail
gm

@time_it
@

def do_task(task):
73

#..... YOUR CODE STARTS HERE .....


8
raj

task_name, task_duration = task


at
h

time.sleep(task_duration)
ks
(a

#..... YOUR CODE ENDS HERE .....


AJ
TR
HA

if __name__ == "__main__":
S

task_name, duration = list(map(lambda x: x.strip(), input().strip().split(',')))


AK

task = [task_name, int(duration)]

do_task(task)

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Decorating the hall took 2.0 seconds
Compilation Status: Passed
Execution Time:
0.012s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Preparing the food took 3.0 seconds

Compilation Status: Passed

)
m
.co
Execution Time: ail
gm

0.013s
@
738

66. You are organizing a marriage function and you have a list of
raj

tasks to be done. Each task has a time duration. You want to keep
hat

track of the total time taken by all tasks. Write a Python class
ks
(a

MarriageFunction with a class method do_task that simulates doing


AJ

a task and keeps track of the total time taken by all tasks.
TR
HA

Input:
S
AK

task: a tuple. The first element is the task name (a string), and the second element is
the task duration in seconds (an integer).

Output:

The function should print the task name and the time taken by the task in the format:
f"{task[0]} took {round(end - start, 2)} seconds

Sample Input:
[("Decorating the hall", 2)]

Sample Output:
Decorating the hall took 2.0 seconds
Explanation:

The class MarriageFunction has a class method do_task which simulates doing a
task by sleeping for the duration of the task. The method adds the time taken by the
task to the total_duration class variable and prints the task name and the time taken
by the task. This demonstrates how class variables can be used to keep track of state
across multiple method calls. In the context of organizing a marriage function, this
can be useful to keep track of how long all tasks take in total.

Completion Status: Completed

Concepts Included:
gu - functional programming: unit 3

Language Used: PYTHON 3

Source Code:

)
m
.co
import time ail
import re
gm
@

class MarriageFunction:
73

total_duration = 0
8
raj
at

@classmethod
h

def do_task(cls, task):


ks
(a

#..... YOUR CODE STARTS HERE .....


AJ
TR

start_time = time.time()
time.sleep(task[1])
HA

end_time = time.time()
S
AK

duration = end_time - start_time


cls.total_duration += duration
print(f"{task[0]} took {round(duration, 2)} seconds")

#..... YOUR CODE ENDS HERE .....

def replace_non_alphanumeric(text, replacement=''):


return re.sub(r'[^a-zA-Z0-9, ]', replacement, text)

def clean_input(value):
value = replace_non_alphanumeric(value).split(',')

id, price = list(map(lambda x: x.strip(), value))

return (id, int(price))

if __name__ == "__main__":
tasks = input()
tasks = list(map(clean_input, tasks.strip().replace('[', '').replace(']', '').split('),')))

for task in tasks:


MarriageFunction.do_task(task)

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Decorating the hall took 2.0 seconds

)
m
.co
Compilation Status: Passed ail
Execution Time:
gm
@

0.019s
73
8
raj

TestCase2:
at
h
ks

Input:
(a
AJ

< hidden >


TR

Expected Output:
SHA
AK

< hidden >

Output:
Preparing the food took 3.0 seconds

Compilation Status: Passed


Execution Time:
0.026s

67. You are developing a student management system for a B.Tech


program. The system has a function get_student_grade(student_id:
str) -> str that takes a student ID as input and returns the grade of
that student.
The program has the following students enrolled:
Student ID: "BT202101", Grade: "A"

Student ID: "BT202102", Grade: "B"

However, not all students are enrolled in the program at all times. If a student is not
enrolled, the function should raise a StudentNotFoundError with a message "Student
not found".

Write a Python function proxy_get_student_grade(student_id: str) -> str that acts as a


proxy to the get_student_grade(student_id: str) -> str function. The proxy function
should handle any StudentNotFoundError that might be raised and return a default
grade 'N/A' if the student is not found.

Constraints:

Student ID is a string.

You can't install any external libraries.

Sample Input:

)
m
.co
BT202101 ail
Sample Output:
gm
@

A
738

Explanation:
raj
at

In the sample outputs, the first grade is returned when the student is found in the
h
ks

program. The grade of the student is displayed in the output. This is done by catching
(a

the grade returned by the get_student_grade function in a try block.


AJ
TR

This demonstrates how proxy functions work in Python - a proxy function acts as an
HA

interface to another function and can add additional behavior (like error handling)
without changing the original function’s code. In this case, the proxy function adds
S
AK

error handling to the get_student_grade function, allowing it to return a default grade


when a student is not found. This is a key aspect of robust software design.

In Python, functions are first-class objects, which means they can be passed around
and used as arguments just like any other object (string, int, float, list, etc.). Higher-
order functions are a kind of function that takes one or more functions as arguments,
returns a function, or both. This property allows us to create proxy functions like
proxy_get_student_grade.

Completion Status: Completed

Concepts Included:
gu - functional programming: unit 3

Language Used: PYTHON 3


Source Code:
class StudentNotFoundError(Exception):
pass

def get_student_grade(student_id):

students = {
"BT202101": "A",
"BT202102": "B",
}
if student_id in students:
return students[student_id]
else:
raise StudentNotFoundError("Student not found")

def proxy_get_student_grade(student_id):
#..... YOUR CODE STARTS HERE .....

try:

)
m
return get_student_grade(student_id)

.co
except StudentNotFoundError: ail
return 'N/A'
gm
@

#..... YOUR CODE ENDS HERE .....


738

student_id = input()
raj
hat

print(proxy_get_student_grade(student_id))
ks
(a
AJ

Compilation Details:
TR
HA

TestCase1:
S
AK

Input:
< hidden >

Expected Output:
< hidden >

Output:
A

Compilation Status: Passed


Execution Time:
0.011s

TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
B

Compilation Status: Passed


Execution Time:
0.012s

68. You are developing a calculator in Python. The calculator has


four operations: add, subtract, multiply, and divide. Each operation

)
m
is a function that takes two numbers and returns the result of the
operation. .co
ail
gm

Write a Python function calculate(operation: Callable[[float, float], float], num1: float,


@

num2: float) -> float that takes an operation function and two numbers as input and
73

returns the result of the operation. The operation function is a higher-order function
8
raj

that can be any of the four operation functions.


hat

Constraints:
ks
(a
AJ

num1 and num2 are floats.


TR

You can't install any external libraries.


SHA
AK

Sample Input:
add, 1.0, 2.0

Sample Output:
3.0

Explanation:

In the sample outputs, each number is the result of a calculation performed by the
calculate function. The calculate function is a higher-order function, which means it
accepts other functions as arguments and/or returns a function as its result. In this
case, calculate accepts an operation function as an argument and applies it to the
two number arguments.

The operation functions (add, divide) are defined using lambda functions, which are
small anonymous functions defined with the lambda keyword in Python. They can
take any number of arguments but can only have one expression. In this case, each
lambda function takes two arguments and returns the result of a specific arithmetic
operation.

This demonstrates the power and flexibility of higher-order functions and lambda
functions in Python. They allow us to write more modular and concise code by
treating functions as first-class objects, meaning that functions can be passed
around and used as arguments or return values, just like any other objects (strings,
numbers, lists, etc.).

Completion Status: Completed

Concepts Included:
gu - functional programming: unit 3

Language Used: PYTHON 3

Source Code:

)
m
.co
from typing import Callable ail
gm

def calculate(operation: Callable[[float, float], float], num1: float, num2: float) -> float:
@

#..... YOUR CODE STARTS HERE .....


738
raj

return operation(num1, num2)


hat

#..... YOUR CODE ENDS HERE .....


ks
(a
AJ

def clean_input(value):
TR

return str(value.strip())
HA

add = lambda x, y: x + y
S
AK

subtract = lambda x, y: x - y
multiply = lambda x, y: x * y
divide = lambda x, y: x / y if y != 0 else None

operation, num1, num2 = map(clean_input, input().strip().split(','))

func = None

if (operation == 'add'):
func = add

elif (operation == 'subtract'):


func = subtract

elif (operation == 'multiply'):


func = multiply

elif (operation == 'divide'):


func = divide

print(calculate(func, float(num1), float(num2)))

Compilation Details:

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
3.0

)
Compilation Status: Passed

m
Execution Time: .co
ail
gm

0.023s
@
738

TestCase2:
raj
at

Input:
h
ks
(a

< hidden >


AJ
TR

Expected Output:
HA

< hidden >


S
AK

Output:
1.5

Compilation Status: Passed


Execution Time:
0.022s

69. You are developing a student management system for a B.Tech


program. The system has a list of students, where each student is
represented as a dictionary with the following keys: 'id', 'name',
'course', and 'grade'.
Write a Python function iterate_students(students: List[Dict[str, Union[str, int]]]) ->
None that takes a list of students as input and prints each student's details using an
iterator. The details should be printed in the following format: "Student ID: {id}, Name:
{name}, Course: {course}, Grade: {grade}".

Constraints:

The id, name, course are strings and grade is an integer.

You can't install any external libraries.

Sample Input:
[

{"id": "BT202101", "name": "John Doe", "course": "Computer Science", "grade": "A"},

{"id": "BT202102", "name": "Jane Doe", "course": "Electrical Engineering", "grade": "B"},

Sample Output:

)
m
Student ID: BT202101, Name: John Doe, Course: Computer Science, Grade: AStudent
.co
ID: BT202102, Name: Jane Doe, Course: Electrical Engineering, Grade: B
ail
gm

Explanation:
@
73

In the sample output, each line is the result of iterating over the list of students and
8

printing each student’s details. This is done using a for loop, which in Python, creates
raj

an iterator for the list and iterates over it.


hat
ks

Iterators in Python are objects that can be iterated (or looped) over. An object is
(a

called iterable if we can get an iterator from it. Most built-in containers in Python like:
AJ

list, tuple, string, etc. are iterables. The iter() function (which in turn calls the iter()
TR

method) returns an iterator from them.


HA

In this case, the list of students is an iterable and the for loop creates an iterator that
S
AK

iterates over each student in the list. For each student, the student’s details are
printed to the console. This demonstrates the use of iterators in Python to efficiently
loop over an iterable object.

Completion Status: Completed

Concepts Included:
gu - functional programming: unit 3

Language Used: PYTHON 3

Source Code:
import sys
import json
from io import StringIO
def iterate_students(students):
#..... YOUR CODE STARTS HERE .....

for student in students:


print(f"Student ID: {student['id']}, Name: {student['name']}, Course: {student['course']},
Grade: {student['grade']}")

#..... YOUR CODE ENDS HERE .....

def clean_input(value):
value = value.strip()
if (len(value)):
if ('}' not in value):
value += '}'

if ('{' in value and '}' in value):


return json.load(StringIO(value))
return False

)
m
if __name__ == "__main__":

.co
students_list = "" ail
gm

for line in sys.stdin:


@

line = line.strip()
73

students_list += line
8
raj

students_list = list(map(clean_input, students_list.replace('[', '').replace(']', '').split('},')))


at
h

students_list = list(filter(lambda student: isinstance(student, dict), students_list))


ks
(a

iterate_students(students_list)
AJ
TR
HA

Compilation Details:
S
AK

TestCase1:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Student ID: BT202101, Name: John Doe, Course: Computer Science, Grade: A
Student ID: BT202102, Name: Jane Doe, Course: Electrical Engineering, Grade: B

Compilation Status: Passed


Execution Time:
0.018s
TestCase2:
Input:
< hidden >

Expected Output:
< hidden >

Output:
Student ID: BT202103, Name: Alice Smith, Course: Mechanical Engineering, Grade: C
Student ID: BT202104, Name: Bob Johnson, Course: Civil Engineering, Grade: D

Compilation Status: Passed


Execution Time:
0.028s

)
m
.co
ail
gm
@
738
raj
hat
ks
(a
AJ
TR
HA
S
AK

You might also like