TCS NQT Questions and Answers

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

TCS NQT Coding Question 2022 – September Day 1 – Slot 1

Problem Statement –

A chocolate factory is packing chocolates into the packets. The chocolate packets here
represent an array of N number of integer values. The task is to find the empty packets(0) of
chocolate and push it to the end of the conveyor belt(array).

Example 1 :

N=8 and arr = [4,5,0,1,9,0,5,0].

There are 3 empty packets in the given set. These 3 empty packets represented as O should be
pushed towards the end of the array

Input :

8 – Value of N

[4,5,0,1,9,0,5,0] – Element of arr[O] to arr[N-1],While input each element is separated by


newline

Output:

45195000

Example 2:

Input:

6 — Value of N.

[6,0,1,8,0,2] – Element of arr[0] to arr[N-1], While input each element is separated by


newline

Output:
618200

Code

n=int(input())
j=0
L=[0 for i in range(n)]
for i in range(n):
a=int(input())
if a!=0:
L[j]=a
j+=1
for i in L:
print(i,end=" ")

TCS NQT Coding Question 2022 – September Day 1 – Slot 1

Problem Statement –

Joseph is learning digital logic subject which will be for his next semester. He usually tries to
solve unit assignment problems before the lecture. Today he got one tricky question. The
problem statement is “A positive integer has been given as an input. Convert decimal value to
binary representation. Toggle all bits of it after the most significant bit including the most
significant bit. Print the positive integer value after toggling all bits”.

Constrains-

1<=N<=100

Example 1:

Input :

10 -> Integer

Output :

5 -> result- Integer


Explanation:

Binary representation of 10 is 1010. After toggling the bits(1010), will get 0101 which
represents “5”. Hence output will print “5”.

Code

import math

n=int(input())

k=(1<< int(math.log2(n))+1)-1

print(n^k)

TCS NQT Coding Question Day 1 Slot 2 – Question 1

Jack is always excited about sunday. It is favourite day, when he gets to play all day. And
goes to cycling with his friends.

So every time when the months starts he counts the number of sundays he will get to enjoy.
Considering the month can start with any day, be it Sunday, Monday…. Or so on.

Count the number of Sunday jack will get within n number of days.

Example 1:

Input

mon-> input String denoting the start of the month.

13 -> input integer denoting the number of days from the start of the month.

Output :

2 -> number of days within 13 days.


Explanation:

The month start with mon(Monday). So the upcoming sunday will arrive in next 6 days. And
then next Sunday in next 7 days and so on.

Now total number of days are 13. It means 6 days to first sunday and then remaining 7 days
will end up in another sunday. Total 2 sundays may fall within 13 days.

Code

def main():

s = input()

a = int(input())

m={

"mon": 6, "tue": 5, "wed": 4,

"thu": 3, "fri": 2, "sat": 1,

"sun": 0

ans = 0

if a - m[s[:3]] >= 1:

ans = 1 + (a - m[s[:3]]) // 7

print(ans)

if __name__ == "__main__":

main()

TCS NQT Coding Question Day 1 Slot 2 – Question 2


Airport security officials have confiscated several item of the passengers at the security check
point. All the items have been dumped into a huge box (array). Each item possesses a certain
amount of risk[0,1,2]. Here, the risk severity of the items represent an array[] of N number of
integer values. The task here is to sort the items based on their levels of risk in the array. The
risk values range from 0 to 2.

Example :

Input :

7 -> Value of N

[1,0,2,0,1,0,2]-> Element of arr[0] to arr[N-1], while input each element is separated by new
line.

Output :

0 0 0 1 1 2 2 -> Element after sorting based on risk severity

Example 2:

input : 10 -> Value of N

[2,1,0,2,1,0,0,1,2,0] -> Element of arr[0] to arr[N-1], while input each element is separated by
a new line.

Output :

0 0 0 0 1 1 1 2 2 2 ->Elements after sorting based on risk severity.

Explanation:

In the above example, the input is an array of size N consisting of only 0’s, 1’s and 2s. The
output is a sorted array from 0 to 2 based on risk severity.

Code
n = int(input())

arr = []

for i in range(n):

arr.append(int(input()))

for i in sorted(arr):

print(i, end=" ")

TCS NQT Coding Question Day 2 Slot 1 – Question 1

Given an integer array Arr of size N the task is to find the count of elements whose value is
greater than all of its prior elements.

Note : 1st element of the array should be considered in the count of the result.

For example,

Arr[]={7,4,8,2,9}

As 7 is the first element, it will consider in the result.

8 and 9 are also the elements that are greater than all of its previous elements.

Since total of 3 elements is present in the array that meets the condition.

Hence the output = 3.

Example 1:

Input

5 -> Value of N, represents size of Arr

7-> Value of Arr[0]


4 -> Value of Arr[1]

8-> Value of Arr[2]

2-> Value of Arr[3]

9-> Value of Arr[4]

Output :

Example 2:

5 -> Value of N, represents size of Arr

3 -> Value of Arr[0]

4 -> Value of Arr[1]

5 -> Value of Arr[2]

8 -> Value of Arr[3]

9 -> Value of Arr[4]

Output :

Constraints

1<=N<=20

1<=Arr[i]<=10000

Code
import sys

n=int(input())

c=0

m=-sys.maxsize-1

while n:

n-=1

a=int(input())

if a>m:

m=a

c+=1

print(c)

TCS NQT Coding Question Day 2 Slot 1 – Question 2

A supermarket maintains a pricing format for all its products. A value N is printed on each
product. When the scanner reads the value N on the item, the product of all the digits in the
value N is the price of the item. The task here is to design the software such that given the
code of any item N the product (multiplication) of all the digits of value should be
computed(price).

Example 1:

Input :

5244 -> Value of N

Output :
160 -> Price

Explanation:
From the input above

Product of the digits 5,2,4,4

5*2*4*4= 160

Hence, output is 160.

Code

n=input()

p=1

for i in n:

p*=int(i)

print(p)

TCS NQT Coding Question Day 3 Slot 2 – Question 1

A furnishing company is manufacturing a new collection of curtains. The curtains are of two
colors aqua(a) and black (b). The curtains color is represented as a string(str) consisting of a’s
and b’s of length N. Then, they are packed (substring) into L number of curtains in each box.
The box with the maximum number of ‘aqua’ (a) color curtains is labeled. The task here is to
find the number of ‘aqua’ color curtains in the labeled box.

Note :

If ‘L’ is not a multiple of N, the remaining number of curtains should be considered as a


substring too. In simple words, after dividing the curtains in sets of ‘L’, any curtains left will
be another set(refer example 1)

Example 1:

Input :
bbbaaababa -> Value of str

3 -> Value of L

Output:

3 -> Maximum number of a’s

Explanation:

From the input given above.

Dividing the string into sets of 3 characters each

Set 1: {b,b,b}

Set 2: {a,a,a}

Set 3: {b,a,b}

Set 4: {a} -> leftover characters also as taken as another set

Among all the sets, Set 2 has more number of a’s. The number of a’s in set 2 is 3.

Hence, the output is 3.

Example 2:

Input :

abbbaabbb -> Value of str

5 -> Value of L

Output:

2 -> Maximum number of a’s

Explanation:
From the input given above,

Dividing the string into sets of 5 characters each.

Set 1: {a,b,b,b,b}

Set 2: {a,a,b,b,b}

Among both the sets, set 2 has more number of a’s. The number of a’s in set 2 is 2.

Hence, the output is 2.

Constraints:

1<=L<=10

1<=N<=50

The input format for testing

The candidate has to write the code to accept two inputs separated by a new line.

First input- Accept string that contains character a and b only

Second input- Accept value for N(Positive integer number)

The output format for testing

The output should be a positive integer number of print the message(if any) given in the
problem statement.(Check the output in Example 1, Example 2).

Code

str = input()

n = int(input())

max_val = 0
count = 0

for i in range(len(str)):

if i % n == 0:

max_val = max(count, max_val)

count = 0

if str[i] == 'a':

count += 1

if count > max_val:

max_val = count

print(max_val)

TCS NQT Coding Question Day 3 Slot 2 – Question 2

An international round table conference will be held in india. Presidents from all over the
world representing their respective countries will be attending the conference. The task is to
find the possible number of ways(P) to make the N members sit around the circular table such
that.

The president and prime minister of India will always sit next to each other.

Example 1:

Input :

4 -> Value of N(No. of members)

Output :

12 -> Possible ways of seating the members

Explanation:
2 members should always be next to each other.

So, 2 members can be in 2!ways

Rest of the members can be arranged in (4-1)! ways.(1 is subtracted because the previously
selected two members will be considered as single members now).

So total possible ways 4 members can be seated around the circular table 2*6= 12.

Hence, output is 12.

Example 2:

Input:

10 -> Value of N(No. of members)

Output :

725760 -> Possible ways of seating the members

Explanation:

2 members should always be next to each other.

So, 2 members can be in 2! ways

Rest of the members can be arranged in (10-1)! Ways. (1 is subtracted because the previously
selected two members will be considered as a single member now).

So, total possible ways 10 members can be seated around a round table is

2*362880 = 725760 ways.

Hence, output is 725760.

The input format for testing

The candidate has to write the code to accept one input


First input – Accept value of number of N(Positive integer number)

The output format for testing

The output should be a positive integer number or print the message(if any) given in the
problem statement(Check the output in example 1, example2)

Constraints :

2<=N<=50

Code

n = int(input())

fact = [0] * (n + 1)

fact[0] = 1

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

fact[i] = fact[i - 1] * i

print(fact[n - 1] * 2)

TCS NQT Coding Question Day 4 Slot 1 – Question 1

Problem Statement

An intelligence agency has received reports about some threats. The reports consist of
numbers in a mysterious method. There is a number “N” and another number “R”. Those
numbers are studied thoroughly and it is concluded that all digits of the number ‘N’ are
summed up and this action is performed ‘R’ number of times. The resultant is also a single
digit that is yet to be deciphered. The task here is to find the single-digit sum of the given
number ‘N’ by repeating the action ‘R’ number of times.
If the value of ‘R’ is 0, print the output as ‘0’.

Example 1:

Input :

99 -> Value of N

3 -> Value of R

Output :

9 -> Possible ways to fill the cistern.

Explanation:

Here, the number N=99

1. Sum of the digits N: 9+9 = 18


2. Repeat step 2 ‘R’ times i.e. 3 tims (9+9)+(9+9)+(9+9) = 18+18+18 =54
3. Add digits of 54 as we need a single digit 5+4

Hence , the output is 9.

Example 2:

Input :

1234 -> Value of N

2 -> Value of R

Output :

2 -> Possible ways to fill the cistern

Explanation:

Here, the number N=1234

1. Sum of the digits of N: 1+2+3+4 =10


2. Repeat step 2 ‘R’ times i.e. 2 times (1+2+3+4)+(1+2+3+4)= 10+10=20
3. Add digits of 20 as we need a single digit. 2+0=2

Hence, the output is 2.

Constraints:

0<N<=1000

0<=R<=50

The Input format for testing

The candidate has to write the code to accept 2 input(s)

First input- Accept value for N (positive integer number)

Second input: Accept value for R(Positive integer number)

The output format for testing

The output should be a positive integer number or print the message (if any) given in the
problem statement.

Code

s=input()

n=int(input())

sum=0

for i in s:

sum+=int(i)

sum*=n
s=str(sum)

while len(s)>1:

sum=0

for i in s:

sum+=int(i)

s=str(sum)

print(s)

TCS NQT Coding Question Day 4 Slot 1 – Question 2

Problem Statement

Particulate matters are the biggest contributors to Delhi pollution. The main reason behind the
increase in the concentration of PMs include vehicle emission by applying Odd Even concept
for all types of vehicles. The vehicles with the odd last digit in the registration number will be
allowed on roads on odd dates and those with even last digit will on even dates.

Given an integer array a[], contains the last digit of the registration number of N vehicles
traveling on date D(a positive integer). The task is to calculate the total fine collected by the
traffic police department from the vehicles violating the rules.

Note : For violating the rule, vehicles would be fined as X Rs.

Example 1:

Input :

4 -> Value of N

{5,2,3,7} -> a[], Elements a[0] to a[N-1], during input each element is separated by a new
line
12 -> Value of D, i.e. date

200 -> Value of x i.e. fine

Output :

600 -> total fine collected

Explanation:

Date D=12 means , only an even number of vehicles are allowed.

Find will be collected from 5,3 and 7 with an amount of 200 each.

Hence, the output = 600.

Example 2:

Input :

5 -> Value of N

{2,5,1,6,8} -> a[], elements a[0] to a[N-1], during input each element is separated by new
line

3 -> Value of D i.e. date

300 -> Value of X i.e. fine

Output :

900 -> total fine collected

Explanation:

Date D=3 means only odd number vehicles with are allowed.

Find will be collected from 2,6 and 8 with an amount of 300 each.
Hence, the output = 900

Constraints:

 0<N<=100
 1<=a[i]<=9
 1<=D <=30
 100<=x<=5000

The input format for testing

The candidate has to write the code to accept 4 input(s).

First input – Accept for N(Positive integer) values (a[]), where each value is separated by a
new line.

Third input – Accept value for D(Positive integer)

Fourth input – Accept value for X(Positive integer )

The output format for testing

The output should be a positive integer number (Check the output in Example 1, Example e)
if no fine is collected then print ”0”.

Code

n = int(input())

arr = list(map(int, input().split()))

d, x = map(int, input().split())

countEven = 0

countOdd = 0

for i in range(n):
if arr[i] % 2 == 0:

countEven += 1

else:

countOdd += 1

if d % 2 != 0:

if countEven == 0:

print("0")

else:

print(countEven * x)

else:

if countOdd == 0:

print("0")

else:

print(countOdd * x)

TCS NQT Coding Question 2023 – September Day 1 – Slot 1

Problem Statement – An automobile company manufactures both a two wheeler (TW) and a
four wheeler (FW). A company manager wants to make the production of both types of
vehicle according to the given data below:

 1st data, Total number of vehicle (two-wheeler + four-wheeler)=v


 2nd data, Total number of wheels = W
The task is to find how many two-wheelers as well as four-wheelers need to manufacture as
per the given data.
Example :

Input :
200 -> Value of V
540 -> Value of W

Output :
TW =130 FW=70

Explanation:
130+70 = 200 vehicles
(70*4)+(130*2)= 540 wheels

Constraints :

 2<=W
 W%2=0
 V<W

Print “INVALID INPUT” , if inputs did not meet the constraints.

The input format for testing


The candidate has to write the code to accept two positive numbers separated by a new line.

 First Input line – Accept value of V.


 Second Input line- Accept value for W.

The output format for testing

 Written program code should generate two outputs, each separated by a single space character(see
the example)
 Additional messages in the output will result in the failure of test case

code
v=5
w=6
if (w&1)==1 or w<2 or w<=v:
print("INVALID INPUT")
else:
x=((4*v) -w)//2
print("TW={0} FW={1}".format(x,v-x))

TCS NQT Coding Question 2023 – September Day 1 – Slot 1

Problem Statement – Given a string S(input consisting) of ‘*’ and ‘#’. The length of the
string is variable. The task is to find the minimum number of ‘*’ or ‘#’ to make it a valid
string. The string is considered valid if the number of ‘*’ and ‘#’ are equal. The ‘*’ and ‘#’
can be at any position in the string.
Note : The output will be a positive or negative integer based on number of ‘*’ and ‘#’ in the
input string.

 (*>#): positive integer


 (#>*): negative integer
 (#=*): 0

Example 1:
Input 1:

 ###*** -> Value of S

Output :

 0 → number of * and # are equal

code
s="Hello"
a=0
b=0
for i in s:
if i=='*':
a+=1
elif i=='#':
b+=1
print(a-b)

TCS Coding Question Day 1 Slot 2 – Question 1

Given an integer array Arr of size N the task is to find the count of elements whose value is
greater than all of its prior elements.

Note : 1st element of the array should be considered in the count of the result.

For example,
Arr[]={7,4,8,2,9}
As 7 is the first element, it will consider in the result.
8 and 9 are also the elements that are greater than all of its previous elements.
Since total of 3 elements is present in the array that meets the condition.
Hence the output = 3.
Example 1:

Input
5 -> Value of N, represents size of Arr
7-> Value of Arr[0]
4 -> Value of Arr[1]
8-> Value of Arr[2]
2-> Value of Arr[3]
9-> Value of Arr[4]

Output :
3

Example 2:
5 -> Value of N, represents size of Arr
3 -> Value of Arr[0]
4 -> Value of Arr[1]
5 -> Value of Arr[2]
8 -> Value of Arr[3]
9 -> Value of Arr[4]

Output :
5

Constraints

 1<=N<=20
 1<=Arr[i]<=10000

Code

import sys
n=int(input())
c=0
m=-sys.maxsize-1
while n:
n-=1
a=int(input())
if a>m:
m=a
c+=1
print(c)

TCS Coding Question Day 1 Slot 2 – Question 2


A parking lot in a mall has RxC number of parking spaces. Each parking space will either be
empty(0) or full(1). The status (0/1) of a parking space is represented as the element of the
matrix. The task is to find index of the prpeinzta row(R) in the parking lot that has the most
of the parking spaces full(1).

Note :
RxC- Size of the matrix
Elements of the matrix M should be only 0 or 1.

Example 1:
Input :
3 -> Value of R(row)
3 -> value of C(column)
[0 1 0 1 1 0 1 1 1] -> Elements of the array M[R][C] where each element is separated by new
line.
Output :
3 -> Row 3 has maximum number of 1’s

Example 2:
input :
4 -> Value of R(row)
3 -> Value of C(column)
[0 1 0 1 1 0 1 0 1 1 1 1] -> Elements of the array M[R][C]
Output :
4 -> Row 4 has maximum number of 1’s

Code

r=int(input())
c=int(input())
sum=0
m=0
id=0
for i in range(r):
for j in range(c):
sum+=int(input())
if sum>m:
m=sum
id=i+1
sum=0
print(id)

TCS Coding Question Day 2 Slot 1 – Question 1

A party has been organised on cruise. The party is organised for a limited time(T). The
number of guests entering (E[i]) and leaving (L[i]) the party at every hour is represented as
elements of the array. The task is to find the maximum number of guests present on the cruise
at any given instance within T hours.

Example 1:
Input :

 5 -> Value of T
 [7,0,5,1,3] -> E[], Element of E[0] to E[N-1], where input each element is separated by new line
 [1,2,1,3,4] -> L[], Element of L[0] to L[N-1], while input each element is separate by new line.

Output :
8 -> Maximum number of guests on cruise at an instance.

Explanation:

1st hour:
Entry : 7 Exit: 1
No. of guests on ship : 6
2nd hour :
Entry : 0 Exit : 2
No. of guests on ship : 6-2=4

Hour 3:
Entry: 5 Exit: 1
No. of guests on ship : 4+5-1=8

Hour 4:
Entry : 1 Exit : 3
No. of guests on ship : 8+1-3=6

Hour 5:
Entry : 3 Exit: 4
No. of guests on ship: 6+3-4=5
Hence, the maximum number of guests within 5 hours is 8.

Example 2:
Input:
4 -> Value of T
[3,5,2,0] -> E[], Element of E[0] to E[N-1], where input each element is separated by new
line.
[0,2,4,4] -> L[], Element of L[0] to L[N-1], while input each element in separated by new
line

Output:
6
Cruise at an instance

Explanation:
Hour 1:
Entry: 3 Exit: 0
No. of guests on ship: 3
Hour 2:
Entry : 5 Exit : 2
No. of guest on ship: 3+5-2=6

Hour 3:
Entry : 2 Exit: 4
No. of guests on ship: 6+2-4= 4

Hour 4:
Entry: 0 Exit : 4
No. of guests on ship : 4+0-4=0

Hence, the maximum number of guests within 5 hours is 6.


The input format for testing
The candidate has to write the code to accept 3 input.
First input- Accept value for number of T(Positive integer number)
Second input- Accept T number of values, where each value is separated by a new line.
Third input- Accept T number of values, where each value is separated by a new line.
The output format for testing
The output should be a positive integer number or a message as given in the problem
statement(Check the output in Example 1 and Example 2)

Constraints:

 1<=T<=25
 0<= E[i] <=500
 0<= L[i] <=500

Code

import java.util.*;
class Main
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
int t = sc.nextInt ();
int e[] = new int[t];
int l[] = new int[t];
for (int i = 0; i < t; i++)
e[i] = sc.nextInt ();

for (int i = 0; i < t; i++)


l[i] = sc.nextInt ();

int max = 0, sum = 0;


for (int i = 0; i < t; i++)
{
sum += e[i] - l[i];
max = Math.max (sum, max);
}
System.out.println (max);
}
}

TCS Coding Question Day 2 Slot 1 – Question 2

At a fun fair, a street vendor is selling different colours of balloons. He sells N number of
different colours of balloons (B[]). The task is to find the colour (odd) of the balloon which is
present odd number of times in the bunch of balloons.
Note: If there is more than one colour which is odd in number, then the first colour in the
array which is present odd number of times is displayed. The colours of the balloons can all
be either upper case or lower case in the array. If all the inputs are even in number, display
the message “All are even”.

Example 1:

 7 -> Value of N
 [r,g,b,b,g,y,y] -> B[] Elements B[0] to B[N-1], where each input element is sepārated by ṉew
line.

Output :

 r -> [r,g,b,b,g,y,y] -> “r” colour balloon is present odd number of times in the bunch.

Explanation:
From the input array above:

 r: 1 balloon
 g: 2 balloons
 b: 2 balloons
 y : 2 balloons
Hence , r is only the balloon which is odd in number.

Example 2:
Input:

 10 -> Value of N
 [a,b,b,b,c,c,c,a,f,c] -> B[], elements B[0] to B[N-1] where input each element is separated by new
line.

Output :
b-> ‘b’ colour balloon is present odd number of times in the bunch.

Explanation:
From the input array above:

 a: 2 balloons
 b: 3 balloons
 c: 4 balloons
 f: 1 balloons
Here, both ‘b’ and ‘f’ have odd number of balloons. But ‘b’ colour balloon occurs first.
Hence , b is the output.

Input Format for testing


The candidate has to write the code to accept: 2 input

 First input: Accept value for number of N(Positive integer number).


 Second Input : Accept N number of character values (B[]), where each value is separated by a new
line.

Output format for testing


The output should be a single literal (Check the output in example 1 and example 2)

Constraints:

 3<=N<=50
 B[i]={{a-z} or {A-Z}}

Code

import java.util.*;
class Main
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
int n = sc.nextInt ();
char arr[] = new char[n];
for (int i = 0; i < n; i++)
arr[i] = sc.next ().charAt (0);
int lower[] = new int[26];
int upper[] = new int[26];
for (int i = 0; i < n; i++)
{
if ((arr[i] >= 'A') && (arr[i] <= 'Z'))
upper[arr[i] - 'A']++;
else if ((arr[i] >= 'a') && (arr[i] <= 'z'))
lower[arr[i] - 'a']++;
}
boolean flag = false;
char ch = '\0';
for (int i = 0; i < n; i++)
{
if ((arr[i] >= 'A') && (arr[i] <= 'Z'))
{
if (upper[arr[i] - 'A'] % 2 == 1)
{
ch = (char) (arr[i]);
flag = true;
break;
}
}
else if ((arr[i] >= 'a') && (arr[i] <= 'z'))
{
if (lower[arr[i] - 'a'] % 2 == 1)
{
ch = (char) (arr[i]);
flag = true;
break;
}

}
if (flag == true)
System.out.println (ch);
else
System.out.println ("All are even");
}
}

Question 1

T here is a JAR full of candies for sale at a mall counter. JAR has the capacity N, that is

JAR can contain maximum N candies when JAR is full. At any point of time. JAR can have
M number of Candies where M<=N. Candies are served to the customers. JAR is never
remain empty as when last k candies are left. JAR if refilled with new candies in such a way
that JAR get full.
Write a code to implement above scenario. Display JAR at counter with available number of
candies. Input should be the number of candies one customer can order at point of time.
Update the JAR after each purchase and display JAR at Counter.

Output should give number of Candies sold and updated number of Candies in JAR.

If Input is more than candies in JAR, return: “INVALID INPUT”


Given,
N=10, where N is NUMBER OF CANDIES AVAILABLE
K =< 5, where k is number of minimum candies that must be inside JAR ever.
Example 1:(N = 10, k =< 5)
Input Value
3
Output Value
NUMBER OF CANDIES SOLD : 3
NUMBER OF CANDIES AVAILABLE : 7

Example : (N=10, k<=5)

Input Value
0
Output Value
INVALID INPUT NUMBER OF
CANDIES LEFT : 10

Code

total_candies = 10
no_of_candies = int(input())
if no_of_candies in range(1, 6):
print('No. of Candies Sold:',no_of_candies)
print('No. of Candies Left:',total_candies-no_of_candies)
else:
print("Invalid Input")
print('No. of Candies Left:',total_candies)

Question 2

Selection of MPCS exams include a fitness test which is conducted on ground. There will be
a batch of 3 trainees, appearing for running test in track for 3 rounds. You need to record their
oxygen level after every round. After trainee are finished with all rounds, calculate for each
trainee his average oxygen level over the 3 rounds and select one with highest oxygen level
as the most fit trainee. If more than one trainee attains the same highest average level, they all
need to be selected.

Display the most fit trainee (or trainees) and the highest average oxygen level.

Note:

 The oxygen value entered should not be accepted if it is not in the range between 1 and 100.
 If the calculated maximum average oxygen value of trainees is below 70 then declare the trainees
as unfit with meaningful message as “All trainees are unfit.
 Average Oxygen Values should be rounded.

Example 1:
INPUT VALUES
95
92
95
92
90
92
90
92
90

OUTPUT VALUES
Trainee Number : 1
Trainee Number : 3

Note:
Input should be 9 integer values representing oxygen levels entered in order as

Round 1

 Oxygen value of trainee 1


 Oxygen value of trainee 2
 Oxygen value of trainee 3

Round 2
 Oxygen value of trainee 1
 Oxygen value of trainee 2
 Oxygen value of trainee 3

Round 3

 Oxygen value of trainee 1


 Oxygen value of trainee 2
 Oxygen value of trainee 3

Output must be in given format as in above example. For any wrong input final output
should display “INVALID INPUT”

Code

trainee = [[],[],[],[]]
for i in range(3):
for j in range(3):
trainee[i].append(int(input()))
if (trainee[i][-1]) not in range(1,101):
print("invalid input")
for i in range(3):
trainee[3].append((trainee[2][i]+trainee[1][i]+trainee[0][i])//3)
maximum = max(trainee[3])
for i in range(3):
if trainee[3][i] < 70 :
print("Trainee {0} is unfit".format(i+1))
elif trainee[3][i] == maximum:
print("Trainee Number: ",i+1)
Question 3

Problem Statement

A washing machine works on the principle of Fuzzy System, the weight of clothes put inside
it for washing is uncertain But based on weight measured by sensors, it decides time and
water level which can be changed by menus given on the machine control area.

For low level water, the time estimate is 25 minutes, where approximately weight is between
2000 grams or any nonzero positive number below that.

For medium level water, the time estimate is 35 minutes, where approximately weight is
between 2001 grams and 4000 grams.

For high level water, the time estimate is 45 minutes, where approximately weight is above
4000 grams.

Assume the capacity of machine is maximum 7000 grams

Where approximately weight is zero, time estimate is 0 minutes.

Write a function which takes a numeric weight in the range [0,7000] as input and produces
estimated time as output is: “OVERLOADED”, and for all other inputs, the output statement
is

“INVALID INPUT”.

Input should be in the form of integer value –

Output must have the following format –

Time Estimated: Minutes

Example:
Input value
2000
Output value
Time Estimated: 25 minutes

Code

n = int(input())
if n==0:
print("Time Estimated : 0 Minutes")
elif n in range(1,2001):
print("Time Estimated : 25 Minutes")
elif n in range(2001,4001):
print("Time Estimated : 35 Minutes")
elif n in range(4001,7001):
print("Time Estimated : 45 Minutes")
else:
print("INVALID INPUT")

Question 4

Problem Statement

The Caesar cipher is a type of substitution cipher in which each alphabet in the plaintext or
messages is shifted by a number of places down the alphabet.
For example,with a shift of 1, P would be replaced by Q, Q would become R, and so on.
To pass an encrypted message from one person to another, it is first necessary that both
parties have the ‘Key’ for the cipher, so that the sender may encrypt and the receiver may
decrypt it.
Key is the number of OFFSET to shift the cipher alphabet. Key can have basic shifts from 1
to 25 positions as there are 26 total alphabets.
As we are designing custom Caesar Cipher, in addition to alphabets, we are considering
numeric digits from 0 to 9. Digits can also be shifted by key places.
For Example, if a given plain text contains any digit with values 5 and keyy =2, then 5 will be
replaced by 7, “-”(minus sign) will remain as it is. Key value less than 0 should result into
“INVALID INPUT”

Example 1:
Enter your PlainText: All the best
Enter the Key: 1

The encrypted Text is: Bmm uif Cftu

Write a function CustomCaesarCipher(int key, String message) which will accept plaintext
and key as input parameters and returns its cipher text as output.

Code
def ceaser(text,key):
result = ""
# transverse the plain text
for i in range(len(text)):
char = text[i]
# Encrypt uppercase characters in plain text
if (char.isupper()):
result += chr((ord(char) + key-65) % 26 + 65)
# Encrypt lowercase characters in plain text
elif (char.islower()):
result += chr((ord(char) + key - 97) % 26 + 97)
elif(char.isdigit()):
result += str(int(char) + key)
elif(char == '-'):
result += '-'
elif (char.isspace()):
result += " "
return result
#check the above function
text = input("Enter your plain text:")
key = int(input("Enter the key:"))
print(ceaser(text,key))

Question 5

Problem Statement

We want to estimate the cost of painting a property. Interior wall painting cost is Rs.18
per sq.ft. and exterior wall painting cost is Rs.12 per sq.ft.

Take input as
1. Number of Interior walls
2. Number of Exterior walls
3. Surface Area of each Interior 4. Wall in units of square feet
Surface Area of each Exterior Wall in units of square feet

If a user enters zero as the number of walls then skip Surface area values as User may
don’t want to paint that wall.

Calculate and display the total cost of painting the property


Example 1:
6
3
12.3
15.2
12.3
15.2
12.3
15.2
10.10
10.10
10.00
Total estimated Cost : 1847.4 INR
Note: Follow in input and output format as given in above example

Code

interior_walls = int(input())
exterior_walls = int(input())
if interior_walls:
int_walls = []
for i in range(interior_walls):
int_walls.append(float(input()))
if exterior_walls:
ext_walls = []
for i in range(exterior_walls):
ext_walls.append(float(input()))
if exterior_walls < 0 or interior_walls < 0:
print(“Invalid Input”)
exit()
if exterior_walls and interior_walls:
print("Total estimated Cost : ",
(sum(int_walls)*18+sum(ext_walls)*12),"INR")
else:
if exterior_walls:
print("Total estimated Cost : ",sum(ext_walls)*12,"INR")
elif interior_walls:
print("Total estimated Cost : ",sum(int_walls)*18,"INR")
else:
print("Total estimated Cost : 0.0 INR")

Question 6

Problem Statement

A City Bus is a Ring Route Bus which runs in circular fashion.That is, Bus once starts at the
Source Bus Stop, halts at each Bus Stop in its Route and at the end it reaches the Source Bus
Stop again.
If there are n number of Stops and if the bus starts at Bus Stop 1, then after nth Bus Stop, the
next stop in the Route will be Bus Stop number 1 always.
If there are n stops, there will be n paths.One path connects two stops. Distances (in meters)
for all paths in Ring Route is given in array Path[] as given below:
Path = [800, 600, 750, 900, 1400, 1200, 1100, 1500]
Fare is determined based on the distance covered from source to destination stop as Distance
between Input Source and Destination Stops can be measured by looking at values in array
Path[] and fare can be calculated as per following criteria:

 If d =1000 metres, then fare=5 INR


 (When calculating fare for others, the calculated fare containing any fraction value should be
ceiled. For example, for distance 900n when fare initially calculated is 4.5 which must be ceiled to
5)

Path is circular in function. Value at each index indicates distance till current stop from the
previous one. And each index position can be mapped with values at same index in BusStops
[] array, which is a string array holding abbreviation of names for all stops as-
“THANERAILWAYSTN” = ”TH”, “GAONDEVI” = “GA”, “ICEFACTROY” = “IC”,
“HARINIWASCIRCLE” = “HA”, “TEENHATHNAKA” = “TE”, “LUISWADI” =
“LU”, “NITINCOMPANYJUNCTION” = “NI”, “CADBURRYJUNCTION” = “CA”

Given, n=8, where n is number of total BusStops.


BusStops = [ “TH”, ”GA”, ”IC”, ”HA”, ”TE”, ”LU”, ”NI”,”CA” ]

Write a code with function getFare(String Source, String Destination) which take Input as
source and destination stops(in the format containing first two characters of the Name of the
Bus Stop) and calculate and return travel fare.

Example 1:
Input Values
ca
Ca
Output Values
INVALID OUTPUT

Example 2:
Input Values
NI
HA
Output Values
23.0 INR
Note: Input and Output should be in format given in example.
Input should not be case sensitive and output should be in the format INR

Code

import math
def getFare(source,destination):
route=[ [ "TH", "GA", "IC", "HA", "TE", "LU", "NI", "CA"],
[800,600,750,900,1400,1200,1100,1500]
]
fare = 0.0
if not (source in route[0] and destination in route[0]):
print("Invalid Input")
exit()
if route[0].index(source) < route[0].index(destination):
for i in range(route[0].index(source),route[0].index(destination)+1):
fare+=route[1][i]
elif route[0].index(destination) < route[0].index(source):
for i in range(route[0].index(source)+1,len(route[0])):
fare+=route[1][i]
for i in range(0,route[0].index(destination)+1):
fare+=route[1][i]
return float(math.ceil(fare*0.005))
source = input()
destination = input()
fare = getFare(source,destination)
if fare == 0:
print("Invalid Input")
else:
print(fare)

Question 7

Problem Statement

There are total n number of Monkeys sitting on the branches of a huge Tree. As travelers
offer Bananas and Peanuts, the Monkeys jump down the Tree. If every Monkey can eat k
Bananas and j Peanuts. If total m number of Bananas and p number of Peanuts are offered by
travelers, calculate how many Monkeys remain on the Tree after some of them jumped down
to eat.
At a time one Monkeys gets down and finishes eating and go to the other side of the road.
The Monkey who climbed down does not climb up again after eating until the other Monkeys
finish eating.
Monkey can either eat k Bananas or j Peanuts. If for last Monkey there are less than k
Bananas left on the ground or less than j Peanuts left on the ground, only that Monkey can eat
Bananas(<k) along with the Peanuts(<j).
Write code to take inputs as n, m, p, k, j and return the number of Monkeys left on the Tree.
Where, n= Total no of Monkeys
k= Number of eatable Bananas by Single Monkey (Monkey that jumped down last may
get less than k Bananas)
j = Number of eatable Peanuts by single Monkey(Monkey that jumped down last may
get less than j Peanuts)
m = Total number of Bananas
p = Total number of Peanuts
Remember that the Monkeys always eat Bananas and Peanuts, so there is no possibility of k
and j having a value zero

Example 1:
Input Values
20
2
3
12
12

Output Values
Number of Monkeys left on the tree:10
Note: Kindly follow the order of inputs as n,k,j,m,p as given in the above example. And
output must include the same format as in above example(Number of Monkeys left on the
Tree:)
For any wrong input display INVALID INPUT

import java.util.*;
class Monkeys
{
public static void main(String []args)
{
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int j = sc.nextInt();
int m = sc.nextInt();
int p = sc.nextInt();
int atebanana=0 ,atepeanut=0;
if( n<0 && k<0 || j<0 || m<0 || p<0)
{
System.out.println("Invalid Input");
}
else
{
if(k>0)
{
atebanana =m/k;
m=m%k;
}
if(j>0)
{
atepeanut = p/j;
p=p%j;
}
n=n-atebanana-atepeanut;
if((m!=0) || (p!=0))
n=n-1;
System.out.println("Number of Monkeys left on the Tree: "+n);
}
}
}

Question 8

Problem Statement

Chain Marketing Organization has has a scheme for income generation, through which its
members generate income for themselves. The scheme is such that suppose A joins the
scheme and makes R and V to join this scheme then A is Parent Member of R and V who are
child Members. When any member joins the scheme then the parent gets total commission of
10% from each of its child members.
Child members receive commission of 5% respectively. If a Parent member does not have
any member joined under him, then he gets commission of 5%.
Take name of the members joining the scheme as input.
Display how many members joined the scheme including parent member.Calculate the Total
commission gained by each members in the scheme. The fixed amount for joining the scheme
is Rs.5000 on which commission will be generated
SchemeAmount = 5000
Example 1: When there are more than one child members
Input : (Do not give input prompts.Accept values as follows. )
Amit //Enter parent Member as this
Y //Enter Y if Parent member has child members otherwise enter N
Rajesh,Virat //Enter names of child members of Amit in comma separated
Output:(Final Output must be in format given below.)
TOTAL MEMBERS:3
COMISSION DETAILS
Amit: 1000 INR
Rajesh :250 INR
Virat: 250 INR

Example 2: When there is only one child member in the hierarchy


Input :
Amit
Y
Rajesh
Output:
Total Members: 2
Comission Details
Amit: 500 INR
Rajesh: 250 INR

Code

parent = input()
Yes_No = input()
if Yes_No == "N":
print("TOTAL MEMBERS:1\nCOMMISSION DETAILS\n{0}: 250
INR".format(parent))
elif Yes_No == "Y":
child=list(map(str,input().split(",")))
print("TOTAL MEMBERS:{}".format(len(child)+1))
print("COMMISSION DETAILS \n{0}:{1}
INR".format(parent,len(child)*500))
for i in child:
print("{0}:250 INR".format(i))

Question 9

Problem Statement

FULLY AUTOMATIC VENDING MACHINE – dispenses your cuppa on just press of


button. A vending machine can serve range of products as follows:

Coffee

1. Espresso Coffee
2. Cappuccino Coffee
3. Latte Coffee

Tea

1. Plain Tea
2. Assam Tea
3. Ginger Tea
4. Cardamom Tea
5. Masala Tea
6. Lemon Tea
7. Green Tea
8. Organic Darjeeling Tea

Soups

1. Hot and Sour Soup


2. Veg Corn Soup
3. Tomato Soup
4. Spicy Tomato Soup

Beverages

1. Hot Chocolate Drink


2. Badam Drink
3. Badam-Pista Drink
Write a program to take input for main menu & sub menu and display the name of sub
menu selected in the following format (enter the first letter to select main menu):

Welcome to CCD
Enjoy your
Example 1:

Input:
c
1
Output
Welcome to CCD!
Enjoy your Espresso Coffee!

Example 2:
Input:
t
9
Output
INVALID OUTPUT!

Code

menu = [['Espresso Coffee','Cappuucino Coffee','Latte Coffee'], ['Plain


Tea',
'Assam Tea','Ginger Tea','Cardamom Tea','Masala Tea','Lemon
Tea','Green Tea',
'Organic Darjeeling Tea'], ['Hot and Sour Soup','Veg Corn Soup','Tomato
Soup',
'Spicy Tomato Soup'], ['Hot Chocolate Drink', 'Badam Drink',
'Badam-Pista Drink']]
m = input()
if m=='c' or m=='t' or m=='s' or m=='b':
if m=='c':
submenu = int(input())

if submenu in range(3):
print('Welcome to CCD!\nEnjoy your {}!'.format(menu[0]
[submenu-1]))
else:
print("INVALID INPUT")
if m=='t':
submenu = int(input())
if submenu in range(8):
print('Welcome to CCD!\nEnjoy your {}!'.format(menu[1]
[submenu-1]))
else:
print("INVALID INPUT")
if m=='s':
submenu = int(input())
if submenu in range(4):
print('Welcome to CCD!\nEnjoy your {}!'.format(menu[2]
[submenu-1]))
else:
print("INVALID INPUT")
if m=='b':
submenu = int(input())
if submenu in range(3):
print('Welcome to CCD!\nEnjoy your {}!'.format(menu[3]
[submenu-1]))
else:
print("INVALID INPUT")
else:
print("INVALID INPUT!")

Question 10

Problem Statement
A doctor has a clinic where he serves his patients. The doctor’s consultation fees are different
for different groups of patients depending on their age. If the patient’s age is below 17, fees is
200 INR. If the patient’s age is between 17 and 40, fees is 400 INR. If patient’s age is above
40, fees is 300 INR. Write a code to calculate earnings in a day for which one array/List of
values representing age of patients visited on that day is passed as input.
Note:

 Age should not be zero or less than zero or above 120


 Doctor consults a maximum of 20 patients a day
 Enter age value (press Enter without a value to stop):

Example 1:
Input
20
30
40
50
2
3
14
Output
Total Income 2000 INR
Note: Input and Output Format should be same as given in the above example.
For any wrong input display INVALID INPUT
Output Format
Total Income 2100 INR
Code

age = []

for i in range(20):
m = input()
if m == "":
break
elif int(m) in range(0,120):
age.append(int(m))
else:
print("INVALID INPUT")
exit()
fees = 0
for i in age:
if i < 17:
fees+=200
elif i <40:
fees+=400
else:
fees+=300
print("Total Income {} INR".format(fees))

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy