Python E-Lab
Python E-Lab
1. Question Description
Constraints
1≤n≤1000
Input Format:
Output Format:
Code:
n=2
power = int(input())
Thanvi's Maths teacher taught that a sphere is a three-dimensional solid with no face, no edge, no
base and no vertex. It is a round body with all points on its surface equidistant from the center. The
volume of a sphere is
measured in cubic units. Can you help her to find the volume of the sphere for the given radius?
Function Description
Constraints
Take π=3.142
Output Format
Code:
pi = 3.142
r = float(input())
vol = (4/3)*pi*r**3
print(vol)
3. Question Description
Athika and Ritu got a nice job at a MNC company. She was confused with the salary credited in her
account.
Ritu and Athika planned to develop a software that calculates the salary pay if the basic pay was
provided.
The Salary policy of Athika and Ritu's Company is as follows: HRA is 80% of the basic pay and DA is
40% of basic pay.
Constraints
20000<basic≤75000
Input Format
Output Format
Print the Gross salary of employee by adding the certain amount of HRA and DA to the basic pay and
correcting to 2 decimal places.
Code:
basic=float(input())
sal=basic+(basic*0.8)+(basic*0.4)
print(f"{sal:.2f}")
4. Question description
Vetrivel wants to convert the units of time into seconds. He gets the days, hours, minutes, seconds
from the user. Can you help him to convert the units in to seconds.
Input Format
Number of days, hours, minutes and seconds will be given which separated by enter key.
Output Format
Code:
minutes = int(input()) * 60
seconds = int(input())
print(time)
5. Question description
Question description Timothy Boon having the first name Timothy and Last name is Boon. Can you
help him to make a program to display his name as Boon Timothy without using swap function.
Input Format
Output Format
Code
fname = input()
lname = input()
In geometry, the area enclosed by a circle of radius r is nr^2. Here the Greek letter 7 represents a
constant, approximately equal to 3.142, which is equal to the ratio of the circumference of any circle
to its diameter. Subash wants to find the area of circle for the given radius. Can you help him to
calculate the area of circle for the given radius?
Constraints
Subash has to declare the radius named as r with float datatype and pi as 3.142 without importing
math
Input Format
Output Format
Aaron took his girl friend Binita to a restauraunt as he got a job of his dreams.
Binita figured this out and to get back Aaron's confidence she gave him a little task,
When they received the bill for the food they ordered, She asked Aaron to find out the tax amount of
the bill and tip for the meal through a computer code.
Aaron can use your local tax rate when computing the amount of tax owing.
Note:
Tip amount=5%
Constraint:
50 billwt≤1300
Where billwt is the variable you should use for getting the bill amount without tax and tip.
Input format
Single Line of input has single value of type integer representing the Bill Amount Without Tax and Tip
Output format
In First Line Print the calculated Tax with only 2 values after decimal point.
In the Second Line Print the calculated Tip with only 2 values after decimal point.
In the Third Line Print the Total Bill Amount with tax and tip with only 2 values after decimal point.
Code:
#Getting input
Bill_Amount = int(input())
#Assigning Values
Local_Tax = 0.18
Tip = 0.05
#Calculation
Tax = Bill_Amount*Local_Tax
Tip = Bill_Amount*Tip
Total_Bill = Bill_Amount+Tax+Tip
#Print Statements
Vignesh wants to display your details like name, Degree and Branch in the different lines. Can you
help him to program for displaying academic details.
Function Description
Output Format
Refer Testcases.
Code:
name = input()
degree = input()
Ratik a young millionaire deposits $10000 into a bank account paying 7% simple interest per year.
He left the money in for 5 years. He likes to predict the interest and the amount earned by him at the
end of 5 years Can you help him to find the interest and amount resided in his bank account after 5
years?
Functional Description:
amount pinterest.
where p is total principal, i is rate of interest per year, and t is total time in years.
Contraint:
$10000.00≤ p <$250000.00
5.00 ≤ i ≤ 70.00
5≤1≤25
Input Format
Three values representing Principle, Interest per year and Time in Investment of type float, float and
integer respectively and each will be in separate lines.
Output Format
First Line: Print the interest earned for the principle amount in floating point format with 2 values
after decimal point
Second Line: Print the Total amount earned including interest at the end of investment period in
floating point format with 2 values after decimal point
Refer the Testcases for better understand.
Code:
p = float(input())
i = float(input())
t = int(input())
interest = (p*i*t)/100
amount = p+interest
print("Interest after {} Years = ${:.2f}".format(t,interest))
print("Total Amount after {} Years = ${:.2f}".format(t,amount))
10. Question Description
Compute the area of a triangle when the lengths of all three sides are known. Let s1, s2 and s3 be
the lengths of the sides. Let s = (s1 + s2 + s3)/2. Then the area of the triangle can be calculated using
the following formula:
area =sqrt(s x (s - sl) x (s-s2) x (s - s3)) Develop a program that reads the lengths of the sides of a
triangle from the user and displays its area.
Function Description
Constraints
s1,s2,s3>0
Input Format
Output Format
Code:
import math
s1=float(input())
s2=float(input())
s3=float(input())
s = (s1+s2+s3)/2
area = math.sqrt(s*(s-s1)*(s-s2)*(s-s3))
A team from the Royal Squatraclub had planned to conduct a rally to create awareness among the
Pune people to donate eyes. They conducted the rally successfully.
Many of the Pune people realized it and came forward to donate their eyes to the nearby Hospitals.
The eligibility criteria for donating eyes is people should be above 18 and his her weight should be
above 40.
There was a huge crowd and the staff in the eye donation centre found it difficult to manage the
crowd.
So they decided to keep a system and ask the people to enter their age and weight in a system.
Help the blood bank staffs to pick the eligible people for blood donation.
Constraints:
25 ≤ weight ≤ 85
Input format:
Only line of input has two integer values separated by a space representing people age and weight.
Output Format:
Print as either "Eligible for Donation" or "Not Eligible for Donation" based on the condition.
Code:
age = int(input())
weight = int(input())
if age>18 and weight>40:
print("Eligible for Donation")
else:
print("Not Eligible for Donation")
12. Problem Description:
Laasya looking at the friends birthday list on a social media site likes to find if the particular person's
birthday year is a leap year or not.
Since many will have the same doubt she decides to automate the task by writing the code snippet
for finding the same but she don't know the logic to write it.
Constraints:
Input Format:
Output Format:
Print as either NOT A LEAP YEAR or LEAP YEAR after checking the year.
Code:
year = int(input())
if year%4 == 0:
print("LEAP YEAR")
else:
His superior officer ordered him to construct a new building by incorporating equilateral, scalene and
isosceles triangular shapes wherever possible.
Can you clarify his doubt by giving him the correct category of triangle based on the values of sides
given by simon?
Functional Description:
Constraints:
1<=side1<=100
1<=side2<=100
1<=side3<=100
Input Format:
Each line has values of type integer separated by enter key representing 'sidel', 'side2' and 'side3'.
Output Format:
Print as either equilateral or scalene or isosceles triangle based on the values of the sides.
Code:
side1 = int(input())
side2 = int(input())
side3 = int(input())
if(side1==side2 and side2==side3 and side3==side1):
print("Equilateral triangle")
elif(side1==side2 or side2==side3 or side3==side1):
print("Isosceles triangle")
else:
print("Scalene triangle")
14. Question Description:
The cash machine will only accept the transaction if X is a multiple of 5, and Atifa's account balance
has enough cash to perform the withdrawal transaction (including bank charges).
Functional Description:
Calculate and display the Atifa's account staus after the transaction based on the following condition:
If the amount requested the available initial balance-bank charges and or if the requested amount is
not the multiple of 5
In the Second Line of Output Print the Initial Balance with two values after decimal point.
If the amount requested to the available initial balance-bank charges and if the requested amount is
not the multiple of 5
In the First Line of Output Print the Current balance after the successful transaction with two values
after decimal point.
In the Second Line of Output Print the Initial Balance with two values after decimal point.
Constraints:
Input Format:
Only Line of input has two values of type integer and float separated by a space representing the
requested withdrawal amount and the initial account balance respectively.
Output Format:
Print the output based on the condition as per the given format specification.
Code:
requested_amount = int(input())
initial_balance = float(input())
bank_charges = 0.5
else:
current_balance = initial_balance - requested_amount - bank_charges
Shree and Harry was living in the town of Denmark, they usually think and do something innovative
on weekends.
Every day the boys embark on some grand new project, which annoys their controlling sister
candace, who tries to bust them.
One Sunday they were both sitting under a tree in their back yard.
They decide to invent a machine which would allow us to enter 2 numbers it would say whether one
of the entered number is an appropriate value of the other number entered.
Functional Description:
According to their logic a number is said to be an approximate value of the other if they differ by
utmost 0.5. So they decide to insert a logic into the machine but they are finding it difficult can you
help them with the logic?
Constraints:
Input Format:
Each line of input has floating point number separated by an Enter Key representing number1 and
number2 respectively.
Output Format:
Code:
number1 = float(input())
number2 = float(input())
if number2>number1:
approx=number2-number1
if approx<=1:
print("Approximate Number")
else:
else:
approx=number1-number2
if approx<=1:
print("Approximate Number")
else:
Yasir a techie working in a military camp was checking the landmine as per their sequence of
numbers.
Functional Description:
But Major Simon imposes a strict constraint that he should use If else concept to complete the task.
Constraints:
1 ≤ num ≤ 500
-1 ≤ num ≤ -500
Input Format:
Output Format:
Code:
value = int(input())
if value > 0:
print("POSITIVE")
else:
print("NEGATIVE")
17. Problem Description
The School have been opened after lock down so Mrs. Swathy instructed all the Class teachers to
conduct a surprise test to check the progress of her students.
As per instructions test have been conducted and the answer sheets were distributed to the
students.
Upon receiving the papers Swathy asked students from all the classes to calculate their grade based
on the marks they have scored in all the five subjects.
But student were finding it tough calculate the percentage and find their grade accordingly ?
Constraints:
Oss1 ≤100;
0≤ $2≤100;
0≤3≤100;
05s4≤100;
0≤5 ≤100;
If the Percentage
>= 80 - Grade B
>=70-Grade C
>= 60 - Grade D
>= 40-Grade E
Otherwise. Grade F
Input Format:
Each Lines with each values representing the marks of 5 different subjects separated by an enterkey
Output Format:
Print the Percentage and the Grade of the Student in a separate lines respectively.
Code:
s1=int(input())
s2=int(input())
s3=int(input())
s4=int(input())
s5=int(input())
total=s1+s2+s3+s4+s5
avg=total/5
print("{:.2f}".format(avg),"Percent")
if avg>=90:
print("Grade A")
elif avg>=80:
print("Grade B")
elif avg>=70:
print("Grade C")
elif avg>=60:
print("Grade D")
elif avg>=40:
print("Grade E")
else:
print("Grade F")
18. Problem Description:
Caleb and Irfan are purchasing apples which were priced according to their size. But their budget is
minimum.
So they plan to choose one small, one medium and one large apple so that it will fit in their budget.
So can you help them choose the right apple by creating a logic by naming three apples they choose
as applel, apple2,apple3.
Then check the condition if apple2 is greater than applel and apple3 is greater than apple2.
Constraints:
1≤ apple1 ≤600
1≤ apple2 ≤600
1≤ apple3 ≤600
Input format:
First Line: Single number of type integer representing the size of applel
Second Line: Single number of type integer representing the size of apple2
Third Line: Single number of type integer representing the size of apple3
Output Format:
Print as "Fit into Budget" or "Doesn't fit into Budget" based on the condition.
Code:
apple1 = int(input())
apple2 = int(input())
apple3 = int(input())
if apple2 > apple1 and apple3 > apple2:
print("Fit into Budget")
else:
print("Doesn't fit into Budget")
19. Problem Description:
Three brothers want to take a photo with family members. The photographer is capturing the photo
from a long distance.
Some of the family members are standing behind that brothers and those people are not visible to
the photographer.
To get clarity, he asked, "who is the tallest person among those three brothers? But no one
responded clearly.
Can you help the photographer in finding the tallest among the three brothers?
Constraint:
60 ≤ bro1 ≤80
60 bro2 ≤ 80
60 ≤ bro3 ≤ 80
Input Format:
The only line of input has three numbers bro1,bro2 and bro3 of type integers separated by a space
which represents the height of three brothers.
Output Format:
Code:
bro1 = int(input())
bro2 = int(input())
bro3 = int(input())
print(bro1)
print(bro2)
else:
print(bro3)
20. Problem Description
Mr. Issac the Head of Tamil Nadu Meteorological Department have instructed his team members to
analyse the temperature of all the cities in Tamil Nadu.
At the end of analysis the report need to be submitted to him were he expects the temperatures of
cities of Tamil Nadu in Centigrade and the classification of Temperature as "Very Hot" or "Hot" or
"Moderate" for the convenience of reporting it in media interaction.
But the temperatures are usually calculated in the field in Fahrenheit. So people in Tamil nadu
Meteorological Department were finding it tough to convert it to Centigrade and classifying the
temperature for so many cities. Can you help the team members of Issac in doing so
Note:
Constraints:
1s fahrenheit $500
Input Format:
Output Format:
First line: Print the Integer value representing the Temperature in Centigrade
Second Line: Print the temperature Classification as either "Very Hot" or "Hot" or "Moderate".
Code:
fahrenheit = float(input())
celsius = (fahrenheit-32)*5/9;
if celsius>=150:
elif celsius>=100:
print("{:.2f} Centigrade\nHot".format(celsius))
else:
print("{:.2f} Centigrade\nModerate".format(celsius))
21. Question description
For calculating median in ungrouped data, we have to first arrange the items in ascending or
descending order and then median is taken to be the one according to the following:
If the number of observation is odd, we obtain the median from the size of n+12thvalue. If the
number of observation is even, we obtain the median from the arithmetic mean of the n2th and
n+12th value.
Constraints
1≤n≤10
Input Format:
First line is number of elements and second line onwards the data which separated by entry key
Output Format:
Code:
import statistics
lst = []
n = int(input())
for i in range(0,n):
ele = int(input())
lst.append(ele)
if n%2==0:
print(statistics.median(lst))
else:
print(statistics.median(lst))
22. Question Description
In the battle of Kurukshetra, The various vyuhas were studied by the Kauravas and Pandavas alike.
Most of them can be beaten using a counter-measure targeted specifically against that formation. In
the form of battle described in the Mahabharata, it was important to place powerful fighters in
positions where they could inflict maximum damage to the opposing force, or defend their own side.
As per this military strategy, a specific stationary object or a moving object or person could be
captured, surrounded and fully secured during battle. In order to form the triangle pattern by
Pandavas, can you help them to make a program for the pyramid pattern?
Constraints
1≤n≤10
Input Format:
Number of rows will be given as an integer. For example If 6 is entered, then the output will be as in
the below output format
Output Format:
Code:
rows = int(input())
for i in range(rows):
for j in range(i+1):
print("* ",end="")
print("")
23. Question description
Constraints
1<R≤5
1≤C≤5
Input Format:
First line and second line represent the number of rows and columns respectively. Third line onwards
the entries of the matrix separated by entry key
Output Format:
Code:
R = int(input())
C = int(input())
# Initialize matrix
matrix = []
a =[]
a.append(int(input()))
matrix.append(a)
for i in range(R):
for j in range(C):
print()
24. Question Description
In the battle of Kurukshetra, The various vyuhas were studied by the Kauravas and Pandavas alike.
Most of them can be beaten using a counter-measure targeted specifically against that formation. In
the form of battle described in the Mahabharata, it was important to place powerful fighters in
positions where they could inflict maximum damage to the opposing force, or defend their own side.
As per this military strategy, a specific stationary object or a moving object or person could be
captured, surrounded and fully secured during battle. In order to form the triangle pattern by
Pandavas, can you help them to make a program for the pyramid pattern?
Constraints
Input Format:
Number of rows will be given as an integer. For example If 7 is entered, then the output will be as in
the below output format
Output Format:
Code:
rows = int(input())
for i in range(rows+1,0,-1):
for j in range(0,i-1):
print("*",end="")
print("")
25. Question description
Mathematics teacher gave the home work to Pinocchio that addition of square matrices. Can you
help him to find the answer for the problems?
Constraints
2<R<3
2≤C≤3.
Input Format:
First line and second line represent the number of rows and columns respectively. Third line onwards
the entries of the first and second matrices separated by entry key
Output Format:
Refer the Logical test cases.
Code:
r=int(input())
C=int(input())
A=[]
for i in range(r):
a=[]
for j in range(C):
a.append(int(input()))
A.append(a)
B=[]
for i in range(r):
b = []
for j in range(C):
b.append(int(input()))
B.append(b)
for i in range(r):
for j in range(len(A[0])):
print(A[i][j]+B[i][j],end=" ")
print()
26. Problem Description:
Yogesh booked the ticket and went for the magic show with his partner.
Since the magician is popular among general public both married couples and the unmarried youths
will come to his show.
In order to make it convenient for both the set of audience the show organizers have given the
seating arrangement instruction for couples and singles individually.
According to the instruction couples have to sit in the even numbered seats and singles have to sit in
the odd numbered seats.
For better positioning of seats the event organizers would like to develop a seating arrangement
software which will print the layout if the total number of rows for the show is provided.
Constraints:
1 ≤ noofrows ≤ 20
Input Format:
Only line of input has single integer representing the number of rows of seats for the particular day
of the show.
Output Format:
Print the seating layout according to the number of rows provided.
Refer sample testcases for format specification.
Code:
rows = int(input())
for i in range(1,rows+1):
for j in range(1,i+1):
print(i,end=" ")
print("")
27. Question description
Marvel Studios is known for the production of the Marvel Cinematic Universe films, based on
characters that appear in Marvel Comics publications. Marvel counts among its characters such well-
known superheroes as Spider- Man, Iron Man, Captain America, the Hulk, Thor, Wolverine, Ant-Man,
the Wasp, Black Widow, Captain Marvel, Black Panther, Squirrel Girl, Doctor Strange, the Scarlet
Witch, She-Hulk, the Vision, Psylocke, Tigra, Ghost-Spider, the Falcon, the Winter Soldier, Ghost Rider,
Quake, Blade, Daredevil, Ms. Marvel, the Punisher and Deadpool. Superhero teams exist such as the
Avengers, the X-Men, the Fantastic Four and the Guardians of the Galaxy as well as supervillains
including Doctor Doom, Magneto, Thanos, Loki, Green Goblin, Kingpin, Diamondback, Red Skull,
Ultron, the Mandarin, MODOK, Doctor Octopus, Kang, Dormammu, Venom and Galactus. Marvel
decided to create a new story. Can you suggest them that the character names which will be present
in that film to make a film as block buster?
Constraints
Input Format: First line represents number of names involved. Second line onwards the character
names.
Code:
Code:
n = int(input()) # Number of rows
letters = [input() for _ in range(n)] # List of letters
# Loop through each row
for i in range(n):
row = [] # Initialize the row list
# Loop through each letter up to the current row number
for j in range(i+1):
row.append(letters[j] + ' ') # Add the letter and a space to the row list
# Add the remaining spaces to the end of the row
for k in range(n-i-1):
row.append('') # Add two spaces to the row list
print(''.join(row)) # Print the row as a string, joining the letters and spaces with no separator
29. Question description
Euler asked the question to Ramanujan that, from the natural numbers below 10 that are multiples
of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is multiples ? Can you help Ramanujan to
answer the sum of these
Function description
Upper limit of natural number should be get from the user and store it to the variable N.
Constraints
10≤N≤1000
Input Format:
Single line input which represent the natural number
Output Format:
The sum of these multiples will be displayed.
Code:
def sum_of_multiples(N):
total = 0
for i in range(N):
if i % 3 == 0 or i % 5 == 0:
total += i
return total
N = int(input()) # get input from user
print(sum_of_multiples(N)) # calculate and print the sum of multiples
30. Problem Description:
Akash the die heart fan of AR Rahman went to the live concert happened in Bangalore with his family
members.
The event management firm responsible for the event arranged the seats for the audience in
descending order of maximum number of tickets booked for single family.
As per the seating arrangement family with the highest number of people are allotted the seats in
the front rows and the family with the lowest number of people are allotted the seats in the last row.
For the convenience of the seating arrangement volunteers to know how many seat need to be
positioned in each row the event management firm have planned to develop the software which
displays the exact seat layout if the total number of rows is provided.
Can you help them with the logic of doing so?
Constraints:
1 ≤ nooffamilymembers ≤ 20
Input Format:
Only line of input has single integer representing the total number of rows for the concert.
Output Format:
Print the seating arrangement layout based on the number of rows provided.
Refer sample testcases for format specification.
Code:
num_rows = int(input())
for i in range(num_rows):
num_seats = num_rows - i
row_layout = [num_seats] * num_seats
print(*row_layout, end=" ")
print()
31. Problem Description:
Vimal has found two very old sheets of paper, each of which originally contained a string of
lowercase Latin letters. The strings on both the sheets have equal lengths. However, since the sheets
are very old, some letters have become unreadable.
Vimal would like to estimate the difference between these strings. Let's assume that the first string is
named 51, and the second 52. The unreadable symbols are specified with the question mark symbol
"?". The difference between the strings equals to the number of positions i, such that Sii is not equal
to 521, where Sli and 521 denote the symbol at the i the position in 51 and 52, respectively.
Vimal would like to know the minimal and the maximal difference between the two strings, if he
changes all unreadable symbols to lowercase Latin letters.
Now that you're fully aware of Vimal's programming expertise, you might have guessed that he
needs you help solving this problem as well. Go on, help himl
Input Format:
The first line of the input contains an integer I denoting the number of test cases. The description of
T kest cases follows.
The first line of a test case contains a string Si
The second line of a test case contains a string 52.
Both strings consist of lowercase Latin letters and question marks in places where the symbols are
unreadable.
Output Format
For each lest case, output the minimal and the maximal difference between two given strings
separated with a single space.
Constraints
1sTs100
1ST, $2≤100
Explanation:
Assume the given Input string is alle and b
Then you can change the question marks in the strings so that you obtain Slabe and S2 abb. Then $1
and S2 will differ in one position. On the other hand, you can change the letters so that S] abc and 52
bab. Then, the strings will differ in all three positions. So the output will be 13.
Code:
for _ in range(int(input())):
s1=str(input())
s2=str(input())
min_cnt = 0
max_cnt = 0
for i in range(len(s1)):
if s1[i] == '?' or s2[i] == '?':
max_cnt += 1
elif s1[i] != s2[i]:
min_cnt += 1
max_cnt += 1
print(min_cnt, max_cnt)
32. Question description
Janaki set the password of her locker that the possible set of substrings from the string. Can you help
her to set the password?
Constraints
1<len(string)≤10
Input Format:
Refer the test cases
Output Format:
Refer the test cases
Code:
s=str(input())
# Printing all substrings of the string s
for i in range(len(s)):
for j in range(i+1, len(s)+1):
print(s[i:j])
33. Question description:
You are given three strings a, b and a of the same length n. The strings consist of lowercase English
letters only. The ith letter of a is al, the ith letter of b is bi, the ith letter of c is cl.
For every | [1≤≤n) you must swap (i.e. exchange) ci with either ai or bi. So in total you'll perform
exactly n swap operations, each of them either ciai or cibi (ii iterates over all integers between 1 and
n, inclusive).
For example, if a is "code", b is "true", and c is "help", you can make c equal to "crue" taking the 1-st
and the 4-th letters from a and the others from b. In this way a becomes "hodp" and b becomes
"tele".
Is it possible that after these swaps the string a becomes exactly the same as the string b?
Input Format:
The First Line of input contains a string of lowercase English letters
The second Line of input contains a string of lowercase English letters
The third Line of input contains a string of lowercase English letters
Output Format:
Printt lines with answers for all test cases. For each test case:
If it is possible to make string A equal to string B print "YES" (without quotes), otherwise print "NO"
(without quotes)
Function Description:
No particular function is present
Constraints:
1s string size 1000
Explanation:
For example, if a is "code", b is "true", and c is "help", you can make c equal to "crue" taking the 1-st
and the 4th letters from a and the others from b. In this way a becomes "hodp" and b becomes
"tele".
Is it possible that after these swaps the string a becomes exactly the same as the string b?
Code:
t=1
for _ in range(t):
a=(str(input()))
b=(str(input()))
c=(str(input()))
cnt = 0
for i in range(len(a)):
if a[i] == c[i] or b[i] == c[i]:
cnt += 1
if cnt == len(a):
print("YES")
else:
print("NO")
34. Question description
Today Ram is Going to Library for book submission. In Library Ram meet one of his collage life friend
Manoj. Manoj introduced him self to Ram as Data Science engineer at Amazon. Now Ram introduced
him self as Harward Researcher. After that manoj started crying and telling to ram that he is facing a
problem. Ram told him to say his problem.
Manoj told his problem to Ram that he have to perform the following operations:
1. Add two string
2. Exponent of first string
3. Exponent of second string
4. Check whether String B is present in A
5. Check whether String A is present in B
6. Check whether String B not in A
7. Check whether String A not in B
Constraints:
Length of Both Strings is <= 100
Input Format:
Input have two lines:
1. Get first row input
2. Get Second raw input
Output Format:
In Every line you have to print Required Output as mantioneed below:
1. Add two string
2. Exponent of first string
3. Exponent of second string
4. Check whether String B is present in A
5. Check whether String A is present in B
6. Check whether String B not in A
7. Check whether String A not in B
Code:
# Input
str1=input()
str2=input()
#string.find(sub_string)
35. Question description
A long time ago, there resided a person called Geppetto. He was old and lived by himself. He had no
family of his own. Geppetto was a carpenter. He loved to create stuffs from wood. One day, he
thought to make a puppet out
of wood. He said, "I will make a little boy and will call him 'Pinocchio.' First, Geppetto made some
wooden legs and arms. After that, he made the body, and he included hands and feet. Finally, he
made a little boy's head. Geppetto made Pinocchio's eyes, mouth, and nose. After that, he made his
ears. Geppetto worked through out day and night on his wooden puppet. He said to himself, "I wish
Pinocchio were a real boy." A fairy heard you help Pinocchio to find the number of vowels in the
given set of strings.
Geppetto's wish. She decided to grant his wish and make the wooden puppet come to life. She said
to Pinocchio, "You must promise to be a good and honest boy." The next day, Geppetto was very
happy to hear Pinocchio talk.
He loved his wooden son very much. Geppetto smiled. "Now you can go to school with all the other
little boys!". At school, English teacher gave the task to Pinocchio that find the number of vowels in
the given set of strings. Can you help Pinocchio to find the number of vowels in the given set of
strings.
Constraints:
1<t≤5
Input Format:
Refer the Test cases
Output Format:
Refer the Test cases
Code:
# Reading the number of test cases
t = int(input())
# Looping through each test case
for i in range(t):
# Reading the input string
str1=str(input())
# Initializing the vowel count
count = 0
# Looping through each character in the string
for j in range(len(str1)):
# Checking if the character is a vowel
if str1[j] in "aeiouAEIOU":
count += 1
# Printing the vowel count for the current string
print(count)
36. Question description
Sudan and Siva are school mates. They challenge each other to play a game that to arrange string
characters such that lowercase letters should come first
Constraints
1<t<5
Input Format:
Refer the test cases
Output Format:
Refer the test cases
Code:
# Taking input for the number of test cases
t = int(input())
# Looping through each test case
for i in range(t):
# Taking input for the string
str1=str(input())
# Sorting the characters in the string using the sorted() function and the key parameter
sorted_string = sorted(str1, key=lambda x: x.isupper())
Function Description
The factorial of 4 is 4x3x2x1=24
Constraints
0≤n≤500
Input Format:
Refer test cases
Output Format:
Refer test cases
Code:
# Function Program
def factorial(n):
return 1 if (n==1 or n==0) else n * factorial(n - 1)
Constraints
1≤num≤1000
Input
Get the input represents "num"
Output
Print the output where zero is replaced by 7
Code:
def replace_digits(num_str):
return num_str.replace('0', 'x').replace('7', '0').replace('x', '7')
input_str = str(input().strip())
print(replace_digits(input_str))
40. Question Description:
You are given a spreadsheet that contains a list of athletes and their details (such as age, height,
weight and so on). You are required to sort the data based on the th attribute and print the final
resulting table. Follow the example given below for better understanding.
Input Format
The first line contains N and M separated by a space.
The next N lines each contain Melements.
The last line contains K.
Constraints
1≤N,M≤1000
0<K<M
Each element≤1000
Output Format
Print the N lines of the sorted table. Each line should contain the space separated elements. Check
the sample below for clarity.
Code:
# Read the input values
N, M = map(int, input().strip().split(' '))
Function Description
A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam
or nurses run.
Input Format:
Refer a test case
Output Format:
Refer a test case
Code:
# Function which return reverse of a string
def isPalindrome(s):
return s == s[::-1]
if ans:
print("Palindrome")
else:
print("Not Palindrome")
43. Question Description:
Simon wants a number plate for his Brand new luxury car. he likes it to be unrepeatable.
He came through a display board about fibonacci series he wants to check to whether the number he
wants to use for his car comes in fibonacci series or not.
Can you help to them for program which checks if a number is present in fibonacci series or not?
Functional Description:
Perfect square value should be generated for the given number (n) which is multiplied by given
format that is (5*n*n+4) is double equal to one (or) (5*n*n-4) is double equal to one
Constraints:
1<=i<=1000
Input Format:
The only line of input has single integer value representing a car number.
Output Format:
Print "YES" if number belongs to fibonacci, otherwise print as "NO".
Code:
# python program to check if x is a perfect square
import math
# A utility function that returns true if x is perfect square
def isPerfectSquare(x):
s = int(math.sqrt(x))
return s*s == x
# Returns true if n is a Fibonacci Number, else false
def isFibonacci(n):
# n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both
# is a perfect square
return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n*n - 4)
Function Description
145 is a curious number, as 11+41 +51 1+24+120 145.
Constraints
Note: As 11 = 1 and 21 = 2 are not sums they are not included.
10≤n≤500
Input Format:
Refer the test case
Output Format:
Refer the test case
Code:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def sum_of_factorial_digits(n):
total_sum = 0
for digit in str(n):
total_sum += factorial(int(digit))
return total_sum
# Test Cases
num = int(input())
print(sum_of_factorial_digits(num))
45. Question description
Vignesh and Subash had a task that a function that returns the number of prime numbers that exist
up to and including a given number. Can you help them to display the number of primes?
Constraints
2≤n≤10^4
Input Format:
Refer the test case
Output Format:
Refer the test case
Code:
def prime(value):
count=0
for num in range(0, value + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
count+=1
print(count)
val = int(input())
prime(val)
46. Question description
Rani and Raji are sisters they love to compete by playing math games which gradually helped them in
their academics one day.
rani gave her a task to her sister.
The task involves that the program takes kilometers as input and gives the output in miles.
Mandatory: the name of the input variable must be 'k' and the input must be accepted in the form
of float. the name of the object must be 'm'.
But Raji thought she can code a program for this concept but she is finding it difficult.
Can you help her with the suitable logic?
Constraints:
1 < n< 1000000
INPUT:
the first line contains the number of kilometers.
OUTPUT:
print the output in miles.
Code:
class miles:
def __init__(self, k):
self.k = k
def convert(self):
miles = self.k * 0.621371
print("{0} kilometers is equal to {1} miles".format(self.k, miles))
k = float(input())
m = miles(k)
m.convert()
47. Question description
Dhoni is an IT expert who trains youngsters struggling in coding to make them better.
Dhoni usually gives interesting problems to the youngsters to make them love coding.
One such day Dhoni provided the youngsters to solve that the program takes the elements of the list
one by one and displays the average of the elements of the list.
Mandatory: the name of the input variable must be 'n' and it must be of type int. and the name of
the object must be 'obj'
Can you help?
Constraints:
1 < N < 10^5
INPUT:
first-line represents the number of inputs
The next Line represents the inputs values according to the number of inputs
OUTPUT:
The single line represents the average of the given inputs.
Code:
class avg:
def __init__(self, n):
self.n = n
def average(self):
avg=0
for i in range(0,self.n):
num = int(input())
avg+=num
print("Average of elements in the list",round(avg/n,2))
n = int(input())
obj = avg(n)
obj.average()
48. Question description
Rani and Raji are sisters they love to compete by playing math games which gradually helped them in
their academics one day.
rani gave her a task to her sister.
The task involves a string e program takes a string and calculates the length of the string without
using library functions.
Mandatory: must use the function name as "def find(self):" and should use object name as "L" and
should also use "L.find()" But raji thought she can code a program for this concept but she is finding
it difficult.
Can you help her with the suitable logic?
Constraints:
1 < string length < 1000
INPUT:
the first line contains the string.
OUTPUT:
print the result as output.
Code:
class length:
def __init__(self, string):
self.string = string
def find(self):
print("Length of the string is:")
print(len(self.string))
string = input()
L = length(string)
L.find()
49. Question description
Dr. Ramesh is a professor at a university. He is eager to put on a show for pupils as well. During his
lunch break, he decided to host a mind-body activity.
He needs to ask a few thought-provoking questions.
He invited participants to answer questions such that, The program takes two numbers and prints
the LCM of two numbers.
Mandatory: the name of the object must be 'obj' and the name of the class must be 'Icm'
Can you help?
Constraints:
1 < N < 10^5
INPUT:
first-line represents the number
The next Line represents the second input value
OUTPUT:
The single line represents the LCM of the given inputs.
Code:
class lcm:
def __init__(self, a, b):
self.a = a
self.b = b
def find_lcm(self):
i=1
while(1):
if(i % self.a == 0 and i % self.b == 0):
lcm = i
break
i += 1
print("LCM is:", lcm)
Mandatory:
Select operation is,
1. Add
2. Subtract
3. Multiply
4. Divide
Input:
The first line contains the operation of the calculator (1 for add, 2 for sub, 3 for mult, 4 div)
The second line contains the first value
Third line contains the second value
Output:
Displays the output after the operations.
Code:
class calculator:
def __init__(self, choice, num1, num2):
self.choice = choice
self.num1 = num1
self.num2 = num2
def cal(self):
if(self.choice == "1"):
print("{0} + {1} = {2}".format(self.num1,self.num2,self.num1+self.num2))
elif(self.choice == "2"):
print("{0} - {1} = {2}".format(self.num1,self.num2,self.num1-self.num2))
elif(self.choice == "3"):
print("{0} * {1} = {2}".format(self.num1,self.num2,self.num1*self.num2))
elif(self.choice == "4"):
print("{0} / {1} = {2}".format(self.num1,self.num2,self.num1/self.num2))
else:
print("Invalid")
choice = input("")
num1 = int(input())
num2 = int(input())
obj = calculator(choice, num1, num2)
obj.cal()
51. Question description
Nathan was a student by morning and a computer nerd by night
At the earlier stages of his career, he was in need of money,
So he started working in a grocery store, parallelly he did many part-time jobs for daily wages. one
day his part-time class teacher asked a question, Nathan has to identify if the number entered by the
user is positive, negative, or zero.
Constraints:
1 < n < 100000
INPUT:
the first line contains the number.
OUTPUT:
it displays whether it is positive, negative or zero.
Code:
class check:
def __init__(self, num):
self.num = num
def check(self):
if(self.num > 0):
print("+ve")
else:
print("zero")
num = int(input())
obj = check(num)
obj.check()
52. Question description
Dr. Suresh is a professor at a university. He is eager to put on a show for pupils as well. During his
lunch break, he decided to host a mind-body activity.
He needs to ask a few thought-provoking questions.
He invited participants to write the code for the questions such that, the program takes a character
as an input and displays the ascii value of the same.
Mandatory:
the name of the object must be 'obj' and the name of the input variable must be 'c'.
Constraints
0< n <10^5
Input Format
Sigle line represents the input value
Output Format
Single line prints the ASCII for the given inputs
Code:
class ascii:
def __init__(self, ch):
self.ch = ch
def Show(self,c):
self.c = ord(self.ch)
print("The ASCII of'{0}' is {1}".format(self.ch, self.c))
ch = input()
obj = ascii(ch)
obj.Show(ch)
53. Question description
Roopa and Atifa are sisters they love to compete by playing math games which gradually helped
them in their academics one day.
Roopa gave her a task to her sister.
The task involves swapping two strings using class and objects in python concept.
you have to ask from user to enter the value of both the string. After entering a value of the two
strings, just swap the two strings using the third variable.
After swapping the two strings, print the result as output.
But Atifa thought she can code a program for this concept but she is finding it difficult.
Can you help her with the suitable logic?
Constraints:
1 < stringlength < 1000
INPUT:
the first line contains the first string.
the second line contains the second string.
OUTPUT:
print the result as output.
Code:
class swap:
def __init__(self, f_str, s_str):
self.f_str = f_str
self.s_str = s_str
def swap(self):
print("Before swap")
print("First String=",self.f_str)
print("Second String=",self.s_str)
self.temp = self.f_str
self.f_str = self.s_str
self.s_str = self.temp
print("After swap")
print("First String=",self.f_str)
print("Second String=",self.s_str)
f_str = input()
s_str = input()
obj = swap(f_str, s_str)
obj.swap()
54. Question description
Dr. Suresh is a professor at a university. He is eager to put on a show for pupils as well. During his
lunch break, he decided to host a mind-body activity.
He needs to ask a few thought-provoking questions.
He invited participants to write the code for the questions such that, the program takes two numbers
and prints the GCD of two numbers.
Mandatory: the name of the object must be 'g' and the name of the class must be 'gcd'.
Constraints
0< n <10^5
Input Format
First-line represents number 1
Second-line represents number 2
Output Format
Single line prints the GCD number for given inputs
Code:
import fractions
import math
class gcd:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def g(self):
return math.gcd(self.num1, self.num2)
num1 = int(input())
num2 = int(input())
obj = gcd(num1, num2)
print("The GCD is", obj.g())
55. Question description
Sajid was booking a train ticket from Chennai to Delhi for his family. Two of the relatives was
interested in joining that journey from different places with their family members
But, Sajid can book one ticket out of those persons also along with his family members.
He wants to identify the right person to book the train ticket.
These two persons are college students, so he decided to conduct a small coding test to finalize the
person who wants to travel with his family members.
Sajid created one of the basic level questions such that the two persons need to identify the area and
the perimeter for the given rectangle.
Can you help?
Mandatory:
Must use "class rectangle:"
Input:
The first line contains the length of the rectangle and the second line contains the breadth of it.
Output:
Print the area in the first line and the perimeter in the second.
Code:
class rectangle:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
def perimeter(self):
return 2 * (self.length + self.breadth)
# User Input
length = float(input())
breadth = float(input())
# Output
r = rectangle(length, breadth)
print("The area is:", r.area())
print("The perimeter is:", r.perimeter())
56. Question description
John buy a New Car.
In his new car speed meter is in kilometer.
he want to convert kilometer into miles. for that he want to write program that takes kilometers as
input and gives the output in miles.
Mandatory: the name of the input variable must be 'k' and the input must be accepted in the form
of float. the name of the object must be 'm'.
But john thought he can code a program for this concept but he is finding it difficult.
Can you help him with the suitable logic?
Constraints:
1 < n< 1000000
INPUT:
the first line contains the number of kilometers.
OUTPUT:
print the output in miles.
Code:
class miles:
def __init__(self,k):
self.k = k
class kilo_to_miles(miles):
def miles(self):
print("{} kilometers is equal to {} miles".format(self.k,self.k*0.621371))
k = float(input())
m = kilo_to_miles(k)
m.miles()
57. Question description
Manish is an IT expert who trains youngsters struggling in coding to make them better.
Manish usually gives interesting problems to the youngsters to make them love coding.
One such day Manish provided the youngsters to solve that the program takes the elements of the
list one by one and displays the average of the elements of the list.
Mandatory: the name of the input variable must be 'n' and it must be of type int. and the name of
the object must be 'obj'
Can you help?
Constraints:
1 < N < 10^5
INPUT:
first-line represents the number of inputs
The next Line represents the inputs values according to the number of inputs
OUTPUT:
The single line represents the average of the given inputs.
Code:
class avg:
def __init__(self,n):
self.n = n
class val(avg):
def avg_val(self):
average = 0
for i in range(0,self.n):
num = int(input())
average += num
print("Average of elements in the list",round(average/self.n,2))
n = int(input())
obj = val(n)
obj.avg_val()
58. Question description
Mani was booking a flight ticket from Canada to Dubai for his family. Two of the relatives was
interested in joining that journey from different places with their family members
But, Mani can book one ticket out of those persons also along with his family members.
He wants to identify the right person to book the Flight ticket.
These two persons are college students, so he decided to conduct a small coding test to finalize the
person who wants to travel with his family members.
Mani created one of the basic level questions such that the two persons need to identify the area
and the perimeter for the given Square.
Can you help?
Mandatory:
Must use "class Square:"
Input:
The first line contains the length of the Square and the second line contains the breadth of it.
Output:
Print the area in the first line and the perimeter in the second.
Code:
class Circle:
def __init__(self, side):
self.side = side
class Print_area_perimeter(Circle):
def area(self):
return self.side**2
def perimeter(self):
return 4*self.side
l = float(input())
r = Print_area_perimeter(l)
print("The area is:", r.area())
print("The perimeter is:", r.perimeter())
59. Question description
Vijaya and Janki are sisters they love to compete by playing math games which gradually helped
them in their academics one day.
Vijaya gave a task to her sister.
The task involves a string and removes the characters of odd index values in the string.
The task should be completed by using class and objects with inheritance concept in python.
But Janki thought she can code a program for this concept but she is finding it difficult.
Can you help her with the suitable logic?
Constraints:
1 < string length < 1000
INPUT:
the first line contains the string.
OUTPUT:
print the result as output.
Code:
class index:
def __init__(self,string):
self.string = string
def modify(self):
return self.string[::2]
class string_work(index):
def __init__(i, string):
super().__init__(string)
print("Modified string is:")
print(i.modify())
def modify(self):
return super().modify()
# Taking input from the user
input_string = input().strip()
# Creating an object of the string_work class and calling the method to modify the string
string_work(input_string).modify()
60. Question description:
Given a class called Shape that takes one input (side of square) make an inherited class called Square
that prints the area of the Square.
Function Description:
No particular function is required
Constraints:
1 ≤5 ≤ 100
Explanation:
No explanation required
Code:
# Parent class
class square:
# User Input
n = int(input())
class palindrome(string):
def reversecheck(self):
# Reversing the string using slicing
rev = self.my_str[::-1]
Code:
class l_year:
# Initiallization function
def __init__(self,year):
self.year = year
# User input
year = int(input())
# Calling the child class with arguments
obj = leap_year(year)
#Invoking the calc function of child class of leap_year
obj.calc()
63. Question description
Dr. Suresh is a professor at a university. He is eager to put on a show for pupils as well. During his
lunch break, he decided to host a mind-body activity.
He needs to ask a few thought-provoking questions.
He invited participants to write the code for the questions such that, the program takes two numbers
and prints the GCD of two numbers.
Mandatory: the name of the object must be 'g' and the name of the class must be 'gcd'
Constraints
0< n <10^5
Input Format
First-line represents number 1
Second-line represents number 2
Output Format
Single line prints the GCD number for given inputs
Code:
import math
class gcd:
def __init__(self,a,b):
self.a = a
self.b = b
class print_gcd(gcd):
def printf(self):
return math.gcd(self.a, self.b)
a = int(input())
b = int(input())
obj = print_gcd(a,b)
print("The GCD is", obj.printf())
#def Show(self,a,b):
64. Question description
Ram is a graduate student he applied to an MNC company but he does not get typing fast. So he
improves his coding skills to get a job in an MNC company.
His well-wisher suggested that he should practice for certain programs that repeatedly asked
fundamental questions.
After several times, Ram struggled to check the upper case letters and lower case letters in the
sentence. can you help him to calculate the number of upper and lower case letters are present in
the given input?
Can you help him with the suitable logic?
Constraints:
1 < stinglen< 10^5
INPUT:
input the sentence or string
OUTPUT:
print the count of upper case and lower case letters.
Code:
class sentance_case:
def __init__(self,string):
self.string= string
class finder_case(sentance_case):
def up_lw_case(self):
count1=0
count2=0
for i in self.string:
if(i.islower()):
count1=count1+1
elif(i.isupper()):
count2=count2+1
print("The number of lowercase characters is:")
print(count1)
print("The number of uppercase characters is:")
print(count2)
# User input
string = input()
obj = finder_case(string)
obj.up_lw_case()
65. Question Description:
What joy! Prithvi's parents went on a business trip for the whole year and the playful kid is left all by
himself.
Prithvi got absolutely happy.
He jumped on the bed and threw pillows all day long, until...
Today Prithvi opened the cupboard and found a scary nate there.
His parents had left him with duties: he should water their favourite flower all year, each day, in the
morning, in the afternoon and in the evening.
"Wait a second!" thought Prithvi. He knows for a fact that if he fulfils the parents' task in the ith
month of the year, then the flower will grow by a centimetres, and if he doesn't water the flower in
the ith month, then the flower won't grow this month.
Petya also knows that try as he might, his parents won't believe that he has been watering the flower
if it grows strictly less than by & centimetres.
Help Prithvi choose the minimum number of months when he will water the flower, given that the
flower should grow no less than by k centimetres.
Constraints:
0sk≤100
Isis 12
050≤ 100
Input Format:
The first line contains exactly one integer k.
The next line contains twelve space-separated integers: the ith number in the line represents a
Output Format:
Print the only integer the minimum number of months when Prithvi has to water the flower so that
the flower grows no less than by k centimetres.
If the flower can't grow by k centimetres in a year, print-1.
Code:
def min_months_to_water(k, growth_rates):
total_growth = 0
months_watered = 0
# Input
w=int(input())
growth_rates = list(map(int,input().split()))
# Output
print(min_months_to_water(w, growth_rates))
# len(l)
66. Question Description:
Nithya came to visit the twin's Anjali and Manisha and saw that they have many cookies.
The cookies are distributed into bags. As there are many cookies, Nithya decided that it's no big deal
if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they
divide the cookies.
That's why Nithya wants to steal a bag with cookies so that the number of cookies in the remaining
bags was even, that is so that Anjali and Manisha could evenly divide it into two (even O remaining
cookies will do, just as any other even number).
How many ways there are to steal exactly one cookie bag so that the total number of cookies in the
remaining bags was even?
Constraints:
1≤ n ≤100
1≤aj≤ 100
Input Format:
The first line contains the only integer n the number of cookie bags Anjali and Manisha have.
The second line contains n integers a, the number of cookies in the ith bag.
Output Format:
Print in the only line the only number the sought number of ways.
If there are no such ways print 0.
Code:
bags=int(input())
cookies = list(map(int,input().split()))
a = [cookie % 2 for cookie in cookies]
print(a.count(sum(a) % 2))
67. Question description:
Charlie's youngest brother, Rohan, is new to programming.
Since his older brother is such a good programmer, his biggest dream is to outshine him.
Rohan is a student at the famous university where he learns to write programs in Gava.
Today, Rohan was introduced to Gava's unsigned integer datatypes.
Gava has a unsigned integer datatypes of sizes (in bits) a1, a2, a The i'th datatype have size a, bits, so
it can represent every integer between 0 and 29.1 inclusive.
Rohan is thinking of learning a better programming language. If there exists an integer x, such that x
fits in some type i (in a bits) and xx does not fit in some other type / [in a bits) where a a, then Rohan
will stop using Gava.
Your task is to determine Rohan's destiny.
Constraints:
25n≤105
1sas 109
Input Format:
The first line contains integer in the number of Gava's unsigned integer datatypes' sizes.
The second line contains a single-space-separated list of n integers sizes of datatypes in bas
Some datatypes may have equal sizes.
Output Format:
Print "YES" if Rohan will stop using Gava, and "NO" otherwise.
Code:
def will_stop_using_gava(n, sizes):
for i in range(n):
for j in range(n):
if sizes[i] < sizes[j] and (sizes[i] * 2) > sizes[j]:
return "YES"
return "NO"
# Read input
n=int(input())
a=list(map(int,input().split()))
Code:
num_friends=int(input()) # Takes an integer input for the number of friends
n = num_friends
friends=list(map(int,input().split())) # Takes a sequence of integers separated by spaces and converts
them into a list of integers
print(*[friends.index(i + 1) + 1 for i in range(n)]) # Prints the position of each integer in the input
sequence
69. Question description:
A little boy Hridayan entered a clothes shop and found out something very unpleasant: not all
clothes turns out to match. For example, Hridayan noticed that he looks rather ridiculous in a
smoking suit and a baseball cap.
Overall the shop sells n clothing items, and exactly m pairs of clothing items match. Each item has its
price, represented by an integer number of rubles.
Hridayan wants to buy three clothing items so that they matched each other. Besides, he wants to
spend as little money as possible. Find the least possible sum he can spend.
Constraints:
3 ≤ n ≤ 100
0≤ m ≤ n(n-1)/2
1 ≤ a ≤ 106
Input Format:
The first input file line contains integers n and m the total number of clothing items in the shop and
the total number of matching pairs of clothing items
Next line contains n integers a, the prices of the clothing items in rubles.
Next m lines each contain a pair of space-separated integers u; and v₁ Each such pair of numbers
means that the urth and the vith clothing items match each other.
Output Format:
Print the only number the least possible sum in rubles that Hridayan will have to pay in the shop.
If the shop has no three clothing items that would match each other, print "-1" (without the quotes).
Code:
from collections import defaultdict
n,m=map(int,input().split())
I = lambda: map(int, input().split())
A = list(I())
C = defaultdict(int)
for i in range(m):
x, y = sorted(I())
C[(x-1,y-1)] += 1
print(min((A[i]+A[j]+A[k] for i in range(n) for j in range(i) for k in range(j)
if C[(j,i)] and C[(k,i)] and C[(k,j)]), default=-1))
70. Question description:
Once when Pranav studied in the first year at school, his teacher gave the class the following
homework.
She offered the students a string consisting of n small Latin letters; the task was to learn the way the
letters that the string contains are written.
However, as Pranav is too lazy, he has no desire whatsoever to learn those letters. That's why he
decided to lose some part of the string (not necessarily a connected part).
The lost part can consist of any number of segments of any length, at any distance from each other.
However, Pranav knows that if he loses more than k characters, it will be very suspicious.
Find the least number of distinct characters that can remain in the string after no more than k
characters are deleted.
You also have to find any possible way to delete the characters.
Constraints:
1≤n≤105
0sk≤105
Input Format:
The first input data line contains a string whose length is equal to n
The string consists of lowercase Latin letters. The second line contains the number k
Output Format:
Print on the first line the only number m the least possible number of different characters that could
remain in the given string after it loses no more than k characters.
Print on the second line the string that Pranav can get after some characters are lost.
The string should have exactly m distinct characters.
The final string should be the subsequence of the initial string.
If Pranav can get several different strings with exactly m distinct characters, print any of them.
Code:
s = input()
k = int(input())
d=dict()
for char in set(s): # Convert s to a set to process unique characters only
d[char] = s.count(char)
print(len(set(s)))
print(s)
#set()
71. Question description:
In a strategic computer game one has to build defense structures to expand and protect the territory.
Let's take one of these buildings.
At the moment the defense structure accommodates exactly n soldiers.
Within this task we can assume that the number of soldiers in the defense structure won't either
increase or decrease.
Every soldier has a rank some natural number from 1 to k. 1 stands for a private and k stands for a
general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from
having the soldiers of the highest possible rank.
To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each
training session requires one golden coin. On each training session all the n soldiers are present.
At the end of each training session the soldiers' ranks increase as follows.
First all the soldiers are divided into groups with the same rank, so that the least possible number of
groups is formed.
Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier
increases his rank by one.
You know the ranks of all n soldiers at the moment.
Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the
rank k.
Constraints:
1 ≤n, k≤ 100
1≤isn
1≤ajsk
Input Format:
The first line contains two integers n and k. They represent the number of soldiers and the number of
different ranks correspondingly.
The second line contains n numbers in the non-decreasing order. The ith of them, a, represents the
rank of the ith soldier in the defense building.
Output Format:
Print a single integer the number of golden coins needed to raise all the soldiers to the maximal rank.
Code:
n,k=map(int,input().split())
r=list(map(int,input().split()))
c=0
while r.count(k)!=n:
s=set(r)
for i in s:
if i<k:
x=r.index(i)
r[x]+=1
c+=1
print(c)
LEVEL - 2
Constraints:
1 <= km <= 5000
1 <= lpd <= 10
Input Format:
The First line of the input represents the total killometers traveled by ram per day.
The Second line of the input represents litres spent per day.
Output Format:
Print the result in the single line with three values after decimal point.
Code:
a = int(input())
b = float(input())
print("{:.3f}".format(a/b))
73. Problem Description:
Surya was used to wear a smartwatch when he was in the Treadmill and during Cycling.
Surya's Smart watch displays the total workout time in seconds.
But Surya would like to know the time he spent for workout in H:M:S format.
Can you help surya in knowing the time he spent on workout in the prescribed format?
Constraints:
1 <= sec <= 10000
Input Format:
The only line of output represents the workout timing in seconds
Output Format:
In the only line of output print the workout timing of surya in the prescribed format.
Refer sample testcases for format specification.
Code:
seconds = int(input())
S = seconds % 60
H = seconds / 60
M = H % 60
H = H / 60
print("%dH:%02dM:%02dS" % (H, M, S))
74. Problem Description:
Jannu and Preethi both went to Egypt for visiting Pyramids.
On seeing the Pyramids they were in discussion.
During the discussion Jannu asked Preethi, what will be the area of this Pyramid.
Preethi have no idea about it.
Can you help Preethi in calculating the area of this Pyramid?
Functional Description:
Area (height base )/2
Constraints:
1 <= height <= 500
1 <= base <= 500
Input Format:
The only line of input has two floating point values representing height and base respectively
separated by a space.
Output Format:
In the only line of output print the area of the pyramid with only three values after decimal point.
Code:
b,h=map(float, input().split(" "))
print(f"{b*h/2:.3f}")
75. Problem Description:
Nancy is a data scientist. She regularly faces about Terra bytes of data in her work.
One day she was working on an application that collects users address and stores it based on the
type of field it has to be
Unfortunately the application malfunctioned and the data collapsed.
Nancy now has the burden of arranging the users data into their respective field can you help her?
Constraint:
0000 ≤ hno ≤ 9999
100000 ≤ pincode ≤ 999999
1000 ≤ employeelD ≤ 9999
000 ≤ areacode ≤ 999
Input Format:
First line of input represents hno
Second line of input represents pincode
Third line of input represents employeelD
Fourth line of input represents areacode
Output Format:
Print the output as per the format specification in the testcases.
Code:
lst = input().split()
print(f"EmployeeID : {lst[2]}\nArea Code : {lst[3]}\nHouse Number : {lst[0]}\nPincode : {lst[1]}")
76. Problem Description:
Issac loved to do agriculture he worked for a 9-5 job in the week days and dedicated to do agriculture
on the week end.
He dreamed to combine technology and agriculture together in the future. He started with a small
automated automobile that can water the plants when he is not available in the field.
He measured his field in square feet but for generalising his project he wished to convert it to acres.
Can you help him with a code that reads the area of the farmer's field in square feet and display the
area in acres?
Functional Description:
There are 43,560 square feet in an acre.
Constraints:
20000.00≤tractLand≤70000.00
Input format:
Single Line of Input has a tractland's area in square feet of type float.
Output format:
Print the input area of the tractland in square feet and its equivalent area in acres in a single line.
Refer sample testcases for formating information
Code:
square_feet = float(input())
acres = square_feet / 43560
print(f"{square_feet} sq.ft is equal to {acres:.2f} acres")
77. Problem Description:
Flipkart announced the year end stock clearance sale and as apart of they have also conducting the
contest and the users answering the questions asked in the contest can win Moto One Power free of
cost.
The task is to display the first three powers (N^1, N^2, N^3) of the given.
Nishanth was looking to buy Moto One Power.
If you help nishanth in solving the task he will get his favorite mobile. Can you help him?
Constraints:
1 <= N <= 150
Input Format:
Only line of the input has a single integer representing N.
Output Format:
Print the first three powers of N in a single line separated by a space.
Code:
n = int(input())
print(f"{n} {n**2} {n**3}")
78. Problem Description:
Arul and Kani own the farm in the beautiful location of the city were lot of cows was roaming around.
One day Arul and Kani was out of the city. On that day cows have eaten the grasses in the farm which
is circular in structure.
Whem Arul and Kani reached the location they were shocked to see the grass being eaten by crows.
Now they wold like to know for how much area and circumference of the farm the cows have eaten
the grass.
Can you help them finding it.
Functional Description:
Circumference = 2*π*г
Area =π *r*г
π = 3.14
Constraints:
1.00 <=rad <=100.00
Input Format:
The only line of the input represents the radius of the circle of type float.
Output Format:
Print the area in the first line and circumference in the second line with only 2 values after decimal
point.
Code:
r = float(input())
pi = 3.14
print(f"{(pi*r**2):.2f}\n{(2*pi*r):.2f}")
79. Problem Description:
Salima saw a pair of beautiful dress online but she was confused about the metric system used for
the size of the dress.
It was given in feet and inches, even in some countries that primarily use some other metric system.
As Salima knows a little bit of programming she thought of creating a program that gets number of
feet and inches and compute the height of the customer in centimeters.
Functional Description:
One foot is 12 inches.
One inch is 2.54 centimeters.
Constraints:
5≤feet≤7
5≤inches≤7
Input format:
Only line of input has two numbers of type integer representing the feet and inches separated by a
space
Output format:
Print the Height of the customer in centimeters
Code:
h_ft,h_inch = map(int, input().split(" "))
h_inch += h_ft * 12
h_cm = h_inch * 2.54
print("Your height in centimeters is : {:.2f}".format(h_cm))
80. Problem Description:
Arav was a popular maths trainer, he gave a 4 digit number to his students as an assignment.
The Students has to identify ones portion of given number.
But students are confused with the logic for doing so.
Can you help the students with the appropriate logic?
Constraint:
1000 ≤ num ≤ 2600
Input Format:
Only line of input has a single integer representing "num";
Output Format:
Print the Digit at one's place
Explanation:
Let us say Aarav given a number "7821" then the number at one place is "1"
Code:
num = int(input())
print(num%10)
81. Question description
Raja is the first year B.Tech CSE student. He wants to find the determinant of given square matrix.
Can you help him to verify his answer?
Function Description
abcd=ad-bc
Constraints
0≤a,b,c,d≤50 and a, b, c, d are integers.
Input Format:
First line represents the elements of first row separated by space
Second line represents the elements of second row separated by space
Output Format
Print the determinant value
Code:
a,b = map(int, input().split(" "))
c,d = map(int, input().split(" "))
determinant_value = (a*d)-(b*c)
print(determinant_value)
82. Question Description:
This is the 214 -th Programming Contest
The PCs so far have had the following number of problems.
The 1-st through 125-th PCs had 4 problems each.
• The 126-th through 211-th PCs had 6 problems each.
• The 212-th through 214-th PCs have 8 problems each.
Find the number of problems in the N-th PC.
Constraints:
1<N≤214
• All values in input are integers.
Input Format
Input is given from Standard Input in the following format:
Output Format
Print the answer.
Code:
def find_number_of_problems(n):
if n <= 125:
return 4
elif n <= 211:
return 6
else:
return 8
n = int(input())
print(find_number_of_problems(n))
83. Question description
The consumption tax rate in the Republic of SRM is 8 percent.
An energy drink shop in this country sells one can of energy drink for N yen (Japanese currency)
without tax.
Including tax, it will be [1.08xN] yen, where [x] denotes the greatest integer not exceeding x for a real
number x.
If this tax-included price is lower than the list price of 206yen, print Yay!; if it is equal to the list price,
print so-so; if it is higher than the list price, print :(.
Constraints
1<N≤300
N is an integer.
Input Format
Input is given from Standard Input in the following format:
N
Output Format
Print the answer
Code:
N = int(input())
tax_included_price = int(1.08 * N)
Constraints
• 0≤x≤10^5
Input Format
X is the value
Output Format
Print the number of additional coins that he needs to collect before he gets the next prize.
Code:
def coins_needed_for_next_prize(coins_collected):
return 100 - (coins_collected % 100)
X = int(input())
coins_needed = coins_needed_for_next_prize(X)
print(coins_needed)
86. Question description
Rhea Pandey's teacher has asked her to prepare well for the lesson on seasons. When her teacher
tells a month, she needs to say the season corresponding to that month. Write a program to solve
the above task.
• Spring - March to May,
• Summer - June to August,
Autumn - September to November and,
Winter - December to February.
Month should be in the range 1 to 12. If not the output should be "Invalid month".
Input Format
A single line input like 11
Output Format
Print the bellow statement
Season: Autumn
Code:
month = int(input())
if month < 1 or month > 12:
print("Invalid month")
elif month >= 3 and month <= 5:
print("Season:Spring")
elif month >= 6 and month <= 8:
print("Season:Summer")
elif month >= 9 and month <= 11:
print("Season:Autumn")
else:
print("Season:Winter")
87. Question description
The door of ISRO's laboratory is locked with a security code.
The security code is a 4-digit number. We say the security code is hard to enter when it contains two
consecutive digits that are the same.
Function Description
You are given the current security code S. If S is hard to enter, print Bad; otherwise, print Good.
Constraints
Sis a 4-character string consisting of digits.
Input Format
Refer the test case
Output Format
If S is hard to enter, print Bad; otherwise, print Good.
Code:
def check_security_code(S):
for i in range(len(S) - 1):
if S[i] == S[i + 1]:
return 'Bad'
return 'Good'
S = input()
print(check_security_code(S))
#print('Good')
LEVEL - 3
Constraints:
1.0 ≤ base ≤ 20.0
1.0 ≤ exp ≤ 10.0
Input Format:
The first line of the input is a base number
The second line of the input is an exponent.
Output Format:
Print the power of a number as output in a single line.
Code:
num = float(input())
expo = float(input())
print("{:.2f}".format(round(num**expo,2)))
89. Question description
Vignesh wants to Format the following data using a string.format() method. Can you help her?
Given:
totalMoney = 1000
quantity = 3
price = 450
Input Format
A single line input will be given
Output Format
The output will be as follows:
I have 1000 dollars so I can buy 3 football for 450.00 dollars.
Code:
txt = input().split(" ")
print("I have {} dollars so I can buy {} football for {:.2f} dollars.".format(txt[1],txt[0],float(txt[2])))
90. Problem Description
Ford once was going down by loosing all their share values due to the less innovative employees in
their company. They wanted to win their competitor named Ferrari. They recruited a car mechanic
who has the capability to build a racing car.
The car mechanic estimated a time in seconds which will be taken to construct a race car, But the
professionals in Ford wanted the exact time in D:HH:MM:SS, (where D, HH, MM, and SS represent
days, hours, minutes and seconds respectively) to be convinced for funding.
Help them with a suitable logic that can help the car mechanic to convince Ford company.
Constraints:
100 ≤ seconds ≤ 455000
Input Format:
The Only line of input has single value representing the duration in seconds.
Output Format:
Print the duration in days, hours, minutes and seconds in format.
Refer sample test cases for format specification.
Code:
time = int(input())
day = int(time/(24*3600))
time = time % (24*3600)
hour = int(time/3600)
time %= 3600
minutes = int(time/60)
time %= 60
print("The Duration is {} days {} hours {} minutes {} seconds".format(day,hour,minutes,time))
91. Question description
Janaki wants to Convert decimal number to octal using print() output formatting. Can you help her?
Input Format
A single line input will be given
Output Format
Refer the test case
Code:
print((int(input()))+2)
92. Problem Description:
Shiva is part of the popular construction company in Tamilnadu.
They constructed an apartment on the express highway.
The apartment is Trapezium in size.
Shiva is part of budget estimation team so he would like to calculate the Area of that apartment.
Can you help him?
Constraints:
1≤ basel ≤ 500
1 ≤ base2 ≤ 500
1 ≤ height ≤ 500
Input Format:
Only Line of input has three floating point values representing basel base 2 and height separated by a
space
Output Format:
Print the area of the apartment in a single line with two values after decimal point.
Code:
basel, base2, height = map(float, input().split())
area = (basel + base2) * height / 2
print("{:.2f}".format(area))
93. Problem Description:
Madhan was working as a loco pilot in the Indian railways.
He was traveling from one state to another state by train.
The default distance calculation machine shows the total traveling distance in kilometres.
But Madhan would like to know the distance in Meters, Feet, Inches, Centimeters
Can you provide him the distance in as he requests?
Input Format:
Only line of input has single floating point value representing the total kilometres driven by Madhan
Output Format:
Print the distance in Meters, feet, inches and centimetres in a separate line respectively.
Code:
num = float(input())
meter = num*1000
feet = num*3280.84
inch = num*39370.1
cm = num*100000
print("{:.2f} m".format(meter))
print("{:.2f} ft".format(feet))
print("{:.2f} in".format(inch))
print("{:.2f} cm".format(cm))
94. Question Description
Nathan was a student by morning and a computer nerd by night.
At the earlier stages of his career he was in need of money,
So he started working in a grocery store. In the grocery store he need to get the product ID, price of
the product(Price per Unit) and the quantity of the product purchased by the customer.
At point of time he found he was doing the same job again and again so he thought of automating
the task.
Help Nathan for framing the code for his work.
Constraint:
1000 ≤ billid ≤ 9999
1000 ≤ prodid ≤ 9999
10.00 ≤ price ≤ 500.00
1 ≤ quantity ≤ 500
Input Format:
First line has the bill id in integer format
Second line has the product id in integer format
Third line contains the product's price in float format
Fourth line contains the quantity of purchased items in integer format
Output Format:
Print the bill amount correct to 2 decimal places corresponding to the bill id.
Code:
bill_id = int(input())
product_id = int(input())
product_price = float(input())
quantity = int(input())
print("{:.2f}".format(product_price*quantity))
95. Question description
Sudhan is visiting a shop specializing in cabbage.
The shop sells cabbage for X yen (Japanese currency) per head.
However, if you buy more than AA heads of cabbage at once, the (A+1)-th and subsequent heads will
be sold for Y yen per head.
(It is guaranteed that Y<X. See Sample Input/Output 1 for clarity.)
Print the amount of money needed to buy Nheads of cabbage.
Constraints
1≤≤10^5
1 \leq A \leq 10^51≤A≤10^5
1 \leq Y \lt X \leq 1001≤Y<X<100
• All values in input are integers.
Input Format
NAAXXYY
Output Format
Print the amount of money needed to buy NN heads of cabbage (as an integer).
Code:
def cabbage_cost(N, A, X, Y):
if N <= A:
return N * X
else:
return A * X + (N - A) * Y
# Input
N, A, X, Y = map(int, input().split())
# Output
print(cabbage_cost(N, A, X, Y))
96. Question description
Mathematics teacher gave the different set of assignments for the poor students. They have to find
the
the count of that number between A and B (inclusive) that is a multiple of C.
Can you help him to print the count of that numbers between A and B, if there is no such number,
print -1?
Constraints
• 1≤A<B≤1000
1≤C≤1000
• All values in input are integers.
Input Format
A BB CC
Output Format
Print the answer.
If there is no number with the desired property, print -1.
Code:
def abc220a():
def count_multiples(A, B, C):
count = 0
for num in range(A, B + 1):
if num % C == 0:
count += 1
return count if count > 0 else -1 # Changed -12 to -1
# Input
A, B, C = map(int, input().split())
# Output
print(count_multiples(A, B, C))
Constraints:
1≤ n ≤109
Input Format:
The first line contains integer n the number of books in the library.
Output Format:
Print the number of digits needed to number all the books.
Code:
def task(n):
s = len(str(n)) # Convert n to string to get its length
return s
def book(s):
return s
n=int(input())
s = task(str(n)) # Convert n to string when calling task function
result = book(s)
print(int(n)*s+s-int('1'*s))
98. Question Description:
Riyaz has given a rectangular board of Mx N squares. Also you are given an unlimited number of
standard domino pieces of 2 x 1 squares. You are allowed to rotate the pieces. You are asked to place
as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
Constraints:
1≤M≤N≤16
Input Format:
In a single line you are given two integers M and N board sizes in squares.
Output Format:
Output one number the maximal number of dominoes, which can be placed.
Code:
def domino(m,n):
total_squares = m * n
domino = total_squares // 2
return round(domino/2)
# Input
m, n = map(int, input().split())
# Output
print(domino(m,n))
99. Question description
Manikandan is a B.Tech student. Math teacher gave the task to him for find the value of NCr?
Can you help him to find the solution?
Function Description
NCr=n!(n-r)! rl
Constraints
n≤r, n>0
Input Format:
First line represents the value of n
Second line represents the value of r
Output Format:
Refer the test case
Code:
import math
def calculate_NCr(n, r):
# Check if constraints are met
if n <= r or n <= 0:
return "Invalid input. Please ensure n > r and n > 0."
# Calculate NCr
result = math.factorial(n) / (math.factorial(r) * math.factorial(n - r))
return result
# Input
n = int(input())
r = int(input())
Constraints:
1≤ n ≤ 100
Input Format:
The first input line contains integer n amount of numbers in the sequence.
The second line contains n space-separated integer numbers elements of the sequence.
These numbers don't exceed 100 in absolute value.
Output Format:
Output index of number that differs from the others in evenness.
Numbers are numbered from 1 in the input order.
Code:
def statistics(l):
# Initialize min1 and min2 variables with large values
min1 = min2 = float('inf')
# Input
n = int(input())
sequence = list(map(int, input().split()))
# Output
result = statistics(sequence)
print(result)