3.Control Flow Statements_3
3.Control Flow Statements_3
Practices# :3
1. You are given a positive integer n. The task is to calculate the sum of its
digits, where the most significant digit (leftmost) is assigned a positive
sign, and each subsequent digit has an opposite sign compared to its
adjacent digits.
Rules:
The most significant digit is positive.
The sign alternates between positive and negative for each
consecutive digit.
Constraints:
Input Format:
A single positive integer n.
Output Format:
A single integer representing the signed sum of the digits.
Input 52 111
Output 3 1
2. Alice and Bob take turns playing a game, with Alice starting first. Initially,
there is a number n on the chalkboard. On each player's turn, that player
makes a move consisting of:
Choosing any x with 0 < x < n and n % x == 0.
Replacing the number n on the chalkboard with n - x.
Also, if a player cannot make a move, they lose the game.
Return true if and only if Alice wins the game, assuming both players play
optimally.
Constraints:
1 ≤ n ≤ 1000
Constraints:
1 ≤ n ≤ 231–1
Input n = 19 n=2
Constraints:
-231 ≤ n ≤ 231–1
Constraints:
Constraints:
1 ≤ n ≤ 1000
Input 8 1
Output 6 1
7. You are given an integer n, the number of teams in a tournament that has
strange rules:
If the current number of teams is even, each team gets paired with
another team. A total of n / 2 matches are played, and n / 2 teams
advance to the next round.
If the current number of teams is odd, one team randomly advances
in the tournament, and the rest gets paired. A total of (n - 1) / 2
matches are played, and (n - 1) / 2 + 1 teams advance to the next
round.
Return the number of matches played in the tournament until a winner is
decided.
Constraints:
1 ≤ n ≤ 200
Input 7 14
Output 6 13
8. You are given two integers, num and t. An integer x is called achievable if it
can become equal to num after applying the following operation no
more than t times:
Increase or decrease x by 1, and simultaneously increase or
decrease num by 1.
Return the maximum possible achievable number. It can be proven that there
exists at least one achievable number.
Constraints:
1 ≤ num, t ≤ 50
Output 6 7
9. The user is asked to take a number as integer n and find out the possible
number of handshakes. For example, if there are n number of people in a
meeting and find the possible number of handshakes made by the person
who entered the room after all were settled.
For the first person, there will be N-1 people to shake hands with
For second person, there will be N -1 people available but as he has
already shaken hands with the first person, there will be N-1-1 = N-2
shake-hands
For third person, there will be N-1-1-1 = N-3, and So On…
Therefore, the total number of handshake = (N – 1 + N – 2 + ...+ 1 + 0) =
((N-1) *N) / 2.
Constraints:
1 ≤ n ≤ 106
Sample test Cases
Test Cases Test Case 1: Test Case 2:
Input 3 5
Output 3 10
10.Write a program to find whether the mobile chosen is within the budget or
not. To find the budget mobiles is based on the below-mentioned criteria,
a) If the cost of the mobile chosen is less than or equal to 15000 then
display it as "Mobile chosen is within the budget" b) If the cost of the
mobile chosen is greater than 15000 then display it as “Mobile chosen is
beyond the budget”.
Constraints:
Output Mobile chosen is within the budget Mobile chosen is beyond the budget
11.You are climbing a staircase. It takes n steps to reach the top. Each time
you can either climb 1 or 2 steps. In how many distinct ways can you climb
to the top?
Constraints:
1 ≤ n ≤ 45
Input 2 3
Output 2 3
12.Smith and John, grade 3 students playing number games. When Smith gives
a number John will say the natural numbers up to that number but in
reverse
order. Shia, their friend will say the sum of those numbers. Help John and
Smith with your program.
Constraints:
Input 5 0
Output Reverse order: [5, 4, 3, 2, 1], Sum: 15 Please enter a natural number greater
than 0.
Constraints:
Valid range:
1000 ≤ n ≤ 9999
Constraints:
1 ≤ n ≤ 109 (as n can be large, but ensure calculations do not result in division by
zero).
Input 3 10
Output 2 285
def michael_game(number):
operations=0
results=0
for i in range(number-1,0,-1):
if(operations==0):
results*=i
elif(operations==1):
results/=i
elif(operations==2):
results+=i
elif(operations==3):
results-=i
operations=operations%4
return results
print(michael_game(int(input())))
15.You are given a positive integer N, and you have to find the number of ways
to represent N as a sum of cubes of two integers(let’s say A and B), such
that:
N = A^3 + B^3.
Note:
A should be greater than or equal to one (A>=1).
B should be greater than or equal to zero (B>=0).
(A, B) and (B, A) should be considered different solutions, if A is not
equal to B, i.e (A, B) and (B, A) will not be distinct if A=B.
Constraints:
1 ≤ T≤ 103
1 ≤ N≤ 108
Input 9 27
Output 2 1
def cubing(number):
count=0
for i in range(1,number+1):
for j in range(0,number+1):
sum = 0
if(i!=j):
sum+=pow(i,3)+pow(j,3)
if(number==sum):
count+=1
return count
number=int(input())
print(cubing(number))
C:\Users\student\PycharmProjects\MEENAMBIGAI_PROBLEMSOLVING\.venv\Scripts\
python.exe C:\Users\student\PycharmProjects\MEENAMBIGAI_PROBLEMSOLVING\.venv\
Scripts\cubing.py
Constraints:
1 ≤ N≤ 100000
Input 3 4
Output 4 7
def fibbo(number):
list1=[]
f1=-1
f2=1
for i in range(number+1):
f3=f1+f2
list1.append(f3)
f1=f2
f2=f3
return sum(list1)
number=int(input())
print(fibbo(number))
C:\Users\student\PycharmProjects\MEENAMBIGAI_PROBLEMSOLVING\.venv\Scripts\
python.exe "C:\Users\student\PycharmProjects\MEENAMBIGAI_PROBLEMSOLVING\.venv\
Scripts\fibonacci indices.py"
Constraints:
1 ≤ k ≤ n ≤ 1000
Input n = 12, k = 3 n = 7, k = 2
Output 3 7
n,k=map(int,input().split(","))
def factors(n,k):
list1=[]
for i in range(1,n+1):
if(n%i==0):
list1.append(i)
if(list1[k]==0):
return -1
else:
print(list1)
return list1[k-1]
print(factors(n,k))
18.You are given two identical eggs and you have access to a building with n
floors labeled from 1 to n.
You know that there exists a floor f where 0 <= f <= n such that any egg
dropped at a floor higher than f will break, and any egg dropped at or
below floor f will not break.
In each move, you may take an unbroken egg and drop it from any floor x
(where 1 <= x <= n). If the egg breaks, you can no longer use it. However,
if the egg does not break, you may reuse it in future moves.
Return the minimum number of moves that you need to determine with
certainty what the value of f is.
Constraints:
1 ≤ n ≤ 1000
Input 2 100
Output 2 14
19.n passengers board an airplane with exactly n seats. The first passenger
has lost the ticket and picks a seat randomly. But after that, the rest of the
passengers will:
Take their own seat if it is still available, and
Pick other seats randomly when they find their seat
occupied Return the probability that the nth person gets his own
seat.
Constraints:
1 ≤ n ≤ 105
Input 1 2
20. Given an integer num, find the closest two integers in absolute
difference whose product equals num + 1 or num + 2.
Return the two integers in any order.
Constraints:
1 ≤ num ≤ 109
Input 8 123
21. There are n friends that are playing a game. The friends are sitting in a
circle and are numbered from 1 to n in clockwise order. More formally,
moving clockwise from the ith friend brings you to the (i+1)th friend for 1
<= i < n, and moving clockwise from the nth friend brings you to the 1st
friend.
The rules of the game are as follows:
Start at the 1st friend.
Count the next k friends in the clockwise direction including the
friend you started at. The counting wraps around the circle and may
count some friends more than once.
The last friend you counted leaves the circle and loses the game.
If there is still more than one friend in the circle, go back to step 2
starting from the friend immediately clockwise of the friend who just
lost and repeat.
Else, the last friend in the circle wins the game.
Given the number of friends, n, and an integer k, return the winner of the
game.
Constraints:
1 ≤ k ≤ n ≤ 1000
Input n = 5, k = 2 n = 6, k = 5
Output 3 1
22. You are given a positive integer arrivalTime denoting the arrival time
of a
train in hours, and another positive integer delayedTime denoting the
amount of delay in hours.
Return the time when the train will arrive at the station.
Note that the time in this problem is in 24-hours format.
Constraints:
1 ≤ arrivalTime < 24
1 ≤ delayedTime ≤ 24
delayedTime = 5 delayedTime = 11
Output 20 0
23. You have 'N' empty pens whose refills have been used up. You have 'R'
rupees in your pocket. You have two choices of operations that you can
perform each time.
Recycle 1 empty pen and get 'K' rupees as a reward.
Buy 1 refill for 'C' rupees and combine it with 1 empty pen to make one
usable pen.
Your task is to find the maximum number of usable pens that you can get.
For example if you have 'N' = 5 , 'R' = 10 , 'K' = 2 , 'C' = 3. You can recycle
one pen and get 2 rupees as a reward so you will have a total of 12 rupees.
Now you can buy 4 refills and combine it with 4 pens to make it usable. So
your answer is 4.
Constraints:
1 ≤ T ≤ 105
1 ≤ N ≤ 109
0 ≤ R ≤ 109
1 ≤ K ≤ 109
1 ≤ C ≤ 109
Input 3 3
10 10 5 5 10 10 1 10
15 11 3 5 5055
3 20 20 2 6042
Output 6 1
7 2
3 4
24. There are numBottles water bottles that are initially full of water. You can
exchange numExchange empty water bottles from the market with one full
water bottle. The operation of drinking a full water bottle turns it into an
empty bottle. Given the two integers numBottles and numExchange, return
the maximum number of water bottles you can drink.
Constraints:
1 ≤ numBottles ≤ 100
2 ≤ numExchange ≤ 100
numExchange = 3 numExchange = 4
Output 13 19
25. Write a program to calculate the fuel consumption of your truck. The
program should ask the user to enter the quantity of diesel to fill up the
tank and the distance covered till the tank goes dry. Calculate the fuel
consumption and display it in the format (liters per 100 kilometers).
Convert the same result to the U.S. style of miles per gallon and display the
result. If the quantity or distance is zero or negative display” is an Invalid
Input”.
[Note: The US approach of fuel consumption calculation (distance/fuel) is
the inverse of the European approach (fuel/distance). Also note that 1
kilometer is 0.6214 miles, and 1 liter is 0.2642 gallons.]
Constraints:
Miles/gallon: 23.45
26. Vohra went to a movie with his friends in a Wave theatre and during break
time he bought pizzas, puffs, and cool drinks. Consider the following
prices :
Rs.100/pizza
Rs.20/puffs
Rs.10/cooldrink
Generate a bill for What Vohra has bought.
Constraints:
The number of pizzas, puffs, and cool drinks must be non-negative integers.
The program should calculate the total cost based on the quantity of each item
purchased.
The output should clearly display the quantities and the total cost, followed by
the message "ENJOY THE SHOW!!!".
Puffs: 5 Puffs: 10
No of pizzas: 3 No of pizzas: 0
No of puffs: 5 No of puffs: 10
No of cooldrinks: 7 No of cooldrinks: 20
27. FOE College wants to recognize the department which has succeeded in
getting the maximum number of placements for this academic year. The
departments that have participated in the recruitment drive are CSE, ECE,
and MECH. Help the college find the department getting maximum
placements. Check for all the possible output.
Constraints:
The number of students placed in each department (CSE, ECE, MECH) must be a
non-negative integer.
If any of the input values is negative, the output should be "Input is Invalid."
If all departments have the same number of placements, the output should be
"None of the department has got the highest placement."
If two or more departments have the highest placements, all such departments
should be listed in the output.
Sample test Cases
Test Cases Test Case 1: Test Case 2: Test Case 3: Test Case 4:
Input CSE: 120, ECE: CSE: 75, ECE: 75, CSE: 85, ECE: -70, CSE: 100, ECE:
placement
28. In a theater, there is a discount scheme announced where one gets a 10%
discount on the total cost of tickets when there is a bulk booking of more
than 20 tickets, and a discount of 2% on the total cost of tickets if a special
coupon card is submitted. Develop a program to find the total cost as per
the scheme. The cost of the k class ticket is Rs.75 and q class is Rs.150.
Refreshments can also be opted by paying an additional of Rs. 50 per
member.
Constraints:
Tickets
29. 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.
Constraints:
The month should be in the range 1 to 12 inclusive. If the month is outside this
range, the output should be "Invalid month".
The program should correctly map each month to its corresponding season:
Spring: March (3) to May (5)
Summer: June (6) to August (8)
Autumn: September (9) to November (11)
Winter: December (12) to February (2)
Constraints:
Input 2: 20 Input 2: 10
31. Goutam and Tanul play by telling numbers. Goutam says a number to
Tanul. Tanul should first reverse the number and check if it is the same as
the original. If yes, Tanul should say “Palindrome”. If not, he should say
“Not a Palindrome”. If the number is negative, print “Invalid Input”. Help
Tanul by writing a program.
Constraints:
If the appraisal rating is between 3.1 and 4, the increment is 25% of the
salary.
If the appraisal rating is between 4.1 and 5, the increment is 30% of the
salary.
Constraints:
The salary should be a positive number. If it's 0 or negative, the output should be
"Invalid Input".
The performance appraisal rating should be in the range of 1 to 5 (inclusive). If
it's not in this range, the output should be "Invalid Input".
The program should handle floating-point values for both salary and appraisal
ratings.
Appraisal
Rating)
33. Chaman planned to choose a four-digit lucky number for his car. His lucky
numbers are 3,5 and 7. Help him find the number, whose sum is divisible by
3 or 5 or 7. Provide a valid car number, fails to provide a valid input then
display that number is not a valid car number.
Constraints:
Constraints:
Search: C++
Output C++ course is C++ course is not Invalid Range Invalid Range
available available
35. Mayuri buys “N” no of products from a shop. The shop offers a different
percentage of discount on each item. She wants to know the item that has
the minimum discount offer, so that she can avoid buying that and save
money.
Constraints:
Input 4 2 3 1
watch,6000,15 pencil,10,5
laptop,35000,5
tablet
36. Raj wants to know the maximum marks scored by him in each semester.
The mark should be between 0 to 100, if goes beyond the range display
“You have entered invalid mark.”
Constraints:
2 3 2 1
78, 84, 92 1st Semester: 40, 35, 70 45, 60, 75, 101
3rd Semester:
50, 60
Output 1st Semester: 92 You have entered 1st Semester: 70 You have entered
37. Bela teaches her daughter to find the factors of a given number. When she
provides a number to her daughter, she should tell the factors of that
number. Help her to do this, by writing a program.
Constraints:
Input 54 -1869 0 29
38. Kochouseph Chittilappilly went to Dhruv Zplanet, a gaming space, with his
friends and played a game called “Guess the Word”.
Computer displays some strings on the screen and the player should pick
one string/word if this word matches with the random word that the
computer picks then the player is declared as
Winner. Kochouseph Chittilappilly’s friends played the game and no one
won the game. This is Kochouseph Chittilappilly’s turn to play and he
decided to must win the game. What he observed from his friend’s game is
that the computer is picking up the string whose length is odd and also that
should be maximum. Due to system failure computers sometimes cannot
generate odd-length words. In such cases, you will lose the game anyways
and it displays “better luck next time”. He needs your help. Check the
below cases for a better understanding.
Constraints:
Input 5 3 1 6
time time
39. Ratan is a crazy rich person. And he is blessed with luck, so he always
made the best profit possible with the shares he bought. That means he
bought a share at a low price and sold it at a high price to maximize his
profit. Now you are an income tax officer and you need to calculate the
profit he made with the given values of stock prices each day. You have to
calculate only the maximum profit Ratan earned.
First line with an integer n, denoting the number of days with the
value of the stock.
Next n days, telling the price of the stock on that very day.
Output Format:
Constraints:
Output 5 0 4 0
40. Stephan is a vampire. And he is fighting with his brother Damon. Vampires
get energy from human blood, so they need to feed on human blood, killing
human beings. Stephan is also less inhuman, so he will like to take less life
in his hand. Now all the people’s blood has some power, which increases
the powers of the Vampire. Stephan just needs to be more powerful than
Damon, killing the least human possible. Tell the total power Stephan will
have after drinking the blood before the
battle.
Note: Damon is a beast, so no human being will be left after Damon drinks
everyone’s blood. But Stephan always comes early to the town.
Input Format:
Output Format:
Constraints:
Input 6 7 5 1
Output 9 9 1 0
41. There are some groups of devils and they split into people to kill them.
Devils make People them left as their group and at last the group with
maximum length will be killed. Two types of devils are there namely “@”
and “$”. People are represented as a string “P”
Input Format:
First line with the string for input.
Output Format:
Number of groups that can be formed.
Constraints:
42. Rohit loves to play with sequences so he has given you a sequence to solve.
To prove to him that you are a good coder, you accept the challenge. Find
the sum of the sequence. Given three integers i, j, k. Find i + (i+1) + (i+2)
+ (i+3) … j + (j-1) + (j-2) + (j-3)..............k
Constraints:
Input i: 5 i: 0 i: 3 i: -2
j: 9 j: 5 j: 3 j: 2
k: 6 k: -1 k: 3 k: -2
Output 56 24 3 0
The candidate has to write the code to accept two positive numbers separated by
a new line.
Additional messages in the output will result in the failure of the test case.
Constraints:
2≤W
W mod 2 = 0 (W should be an even number since wheels are in pairs)
V < W (The number of vehicles should be less than the number of wheels)
Valid Input:
If W mod 2 = 0 and V < W, output the number of two-wheelers and four-wheelers
as per the equations.
Invalid Input:
If W mod 2 != 0 and V ≥ W, print "INVALID INPUT".