python scenario
python scenario
Explanation:
Explanation:
This code calculates the total number of pages read in a month, considering that
the number of pages read per day increases each week.
First, it asks the user to enter the number of pages read per day during the first
week, and the total number of days in the month. These inputs are converted into
integers using int().
The total_pages variable is initialized to 0 to keep track of the total pages read.
The variable pages_per_day is set to the pages read in the first week and
weeks_in_month is calculated by dividing the total days by 7 to get the number of
full weeks. The remaining days after the full weeks are calculated using the
modulus operator (%).
Then, a for loop runs through each week in the month. For each full week, it adds
the pages read to total_pages by multiplying the pages read per day by 7. After
each week, the pages per day are increased by 5.
After the loop, if there are any remaining days (less than a full week), it adds
the pages read for those remaining days to total_pages.
Finally, the print() function displays the total pages read over the month.
Python
xxxxxxxxxx
Explanation:
This code reverses a 3-digit lottery ticket number and displays it as a “reward
code.”
Explanation:
This code determines whether a number is prime, calculates its factorial if it is
prime, and counts the digits in the factorial.
First, the user inputs a number using int(input()), which is stored in the variable
number.
The code initializes is_prime as True, factorial as 1, and digits as 0.
A for loop runs from 1 to the value of number (inclusive). Inside the loop:
It checks if number is divisible by any value other than 1 and itself. If it finds
such a divisor, it sets is_prime to False.
If the number is still considered prime and i is less than or equal to number, the
code multiplies factorial by i to calculate the factorial.
After the loop finishes, the code checks the value of is_prime:
If the number is prime and greater than 1, it prints that the number is prime,
displays the factorial, and counts the digits in the factorial. To count digits, it
converts the factorial to a string using str() and finds its length using len().
If the number is not prime, it simply prints that the number is not prime.
Python
xxxxxxxxxx
# Calculate factorial
if is_prime and i <= number:
factorial *= i
# Check the result of primality
if is_prime and number > 1:
print(f"{number} is a prime number.")
print(f"Factorial of {number} is {factorial}.")
Explanation:
This code simulates a game where you start with a number and perform actions over
several rounds.
First, the code asks the user for the initial_number (starting number) and rounds
(number of rounds to play). A variable count_rounds is initialized to keep track of
the rounds you survive.
The for loop runs for each round, starting from 1 to rounds. In each round:
The code checks if the round number is even or odd.
If it’s even, the number is doubled; if it’s odd, the number is increased by 3.
The next step checks if the number contains the digit ‘7’. This is done by
converting the number to a string using str(number). The str() function allows us
to treat the number as a string so that we can check if ‘7’ is in the string. If
‘7’ is found, the game ends. The message "You lose!" is printed, and the break
statement is used to exit the loop, ending the game early.
If the number doesn’t contain ‘7’, the code checks if it’s divisible by 4. If it
is, the number is halved, and a message is shown. This is done using integer
division (//), which divides the number and keeps it as an integer.
If the number isn’t divisible by 4, a message is displayed saying you survive the
round, and the count_rounds is incremented.
Finally, the code prints how many rounds you survived before losing.
Python
xxxxxxxxxx
if round_num % 2 == 0:
number *= 2
else:
number += 3
It begins by asking for the subject, which can be “Math,” “History,” or any other
subject entered as “Other.” stored in the variable subject.
Then it asks how much time is left for preparation, with options “Less than a week”
or “More than a week,” stored in the variable time.
The program then uses a series of if-elif conditions to determine the appropriate
study plan.
If the subject is “Math,” it checks the value of time.
If the user has “Less than a week,” it suggests focusing on practicing problems to
strengthen problem-solving skills and prints "Suggested Plan: Practice Problems."
If the time left is “More than a week,” it advises reviewing concepts for better
understanding and outputs "Suggested Plan: Concept Reviews."
If the subject is “History,” the program again evaluates the time.
For “More than a week,” it recommends preparing detailed notes for in-depth
understanding and prints "Suggested Plan: Detailed Notes."
If the time is “Less than a week,” it suggests focusing on memorization techniques
for retaining key facts and dates, displaying "Suggested Plan: Memorization
Techniques."
For any subject other than “Math” or “History,” the program handles it under the
“Other” category.
If the user has “More than a week,” it advises thorough study and outputs
"Suggested Plan: Thorough Study."
For “Less than a week,” it recommends quick revision and prioritization of
essential topics, printing "Suggested Plan: Quick Revision."
Python
xxxxxxxxxx
Treasure Hunt
scenario-based coding question on if else with multiple conditions - Treasure Hunt
You are a developer tasked with creating a treasure hunt game. In this game, the
player searches for a hidden treasure at one of four locations. The player has a
couple of tools to find the treasure a key and a map but their success in finding
the treasure depends on whether they have these tools.
Locations:
Location 1: The player can search here, but the treasure is not located there.
Location 2: The map indicates that the treasure might be here, but only players
with a map will receive this clue.
Location 3: This is a decoy location where the treasure is not hidden.
Location 4: The treasure might be locked behind a door, and the player will need a
key to access it.
Rules:
1. The player must first indicate whether they have a key and a map.
2. If the player has a map, they will receive a clue that the treasure may be
hidden at Location
3. If the player chooses Location 4, they will need a key to unlock the door and
collect the treasure.
4. If the player searches in the wrong location (Location 1 or Location 3), they
will be told that the treasure is not there, and they can try again.
The player’s decisions on where to search for the treasure will determine whether
they succeed or not.
Test Case 1:
Input:
Has Key: y
Has Map: y
Location chosen: 2
Expected Output:
Do you have a key? (y/n): y
Do you have a map? (y/n): y
You have a map! The map shows the treasure might be at Location 2.
Choose a location to search for the treasure (1, 2, 3, or 4): 2
Congratulations! You found the treasure at Location 2 using the map!
Test Case 2:
Input:
Has Key: n
Has Map: y
Location chosen: 4
Expected Output:
Do you have a key? (y/n): n
Do you have a map? (y/n): y
You have a map! The map shows the treasure might be at Location 2.
Choose a location to search for the treasure (1, 2, 3, or 4): 4
The treasure is locked behind a door. You need a key to access Location 4!
Question 1
Problem Statement – 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”.
The result should be with two decimal place.To get two decimal place refer the
below-mentioned print statement :
float cost=670.23;
Sample Input 1:
Sample Output 1:
Liters/100KM
13.33
Miles/gallons
17.64
Explanation:
Sample Output 2:
-5 is an Invalid Input
Sample Input 3:
Sample Output 3:
Question-2
Problem Statement – 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.
Sample Input 1:
Bill Details
No of pizzas:10
No of puffs:12
No of cooldrinks:5
Total price=1290
ENJOY THE SHOW!!!
Question-3
Problem Statement – Ritik wants a magic board, which displays a character for a
corresponding number for his science project. Help him to develop such an
application.
For example when the digits 65,66,67,68 are entered, the alphabet ABCD are to be
displayed.
[Assume the number of inputs should be always 4 ]
Sample Input 1:
65-A
66-B
67-C
68-D
Sample Input 2:
115-s
116-t
101-e
112-p
Question-4
Problem Statement – 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, MECH. Help
the college find the department getting maximum placements. Check for all the
possible output given in the sample snapshot
Note : If any input is negative, the output should be “Input is Invalid”. If all
department has equal number of placements, the output should be “None of the
department has got the highest placement”.
Sample Input 1:
Highest placement
CSE
Sample Input 2:
Highest placement
ECE
MECH
Sample Input 3:
Input is Invalid
Question-5
Problem Statement – 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.
Hint: k and q and You have to book minimum of 5 tickets and maximum of 40 at a
time. If fails display “Minimum of 5 and Maximum of 40 Tickets”. If circle is
given a value other than ‘k’ or ‘q’ the output should be “Invalid Input”.
The ticket cost should be printed exactly to two decimal places.
Sample Input 1:
Ticket cost:4065.25
Sample Input 2:
Question-6
Problem Statement – 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.
Sample Input 1:
Season:Autumn
Sample Input 2:
Invalid month
Question-7
Problem Statement – To speed up his composition of generating unpredictable
rhythms, Blue Bandit wants the list of prime numbers available in a range of
numbers.Can you help him out?
Write a java program to print all prime numbers in the interval [a,b] (a and b,
both inclusive).
Note
Input 1 should be lesser than Input 2. Both the inputs should be positive.
Range must always be greater than zero.
If any of the condition mentioned above fails, then display “Provide valid input”
Use a minimum of one for loop and one while loop
Sample Input 1:
2
15
Sample Output 1:
2 3 5 7 11 13
Sample Input 2:
Sample Output 2:
Question-8
Problem Statement – Goutam and Tanul plays by telling numbers. Goutam says a
number to Tanul. Tanul should first reverse the number and check if it is 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.
Sample Input 1 :
21212
Sample Output 1 :
Palindrome
Sample Input 2 :
6186
Sample Output 2 :
Not a Palindrome
Question-9
XYZ Technologies is in the process of increment the salary of the employees. This
increment is done based on their salary and their performance appraisal rating.
If the appraisal rating is between 1 and 3, the increment is 10% of the salary.
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.
Help them to do this, by writing a program that displays the incremented salary.
Write a class “IncrementCalculation.java” and write the main method in it.
Sample Input 1 :
Sample Output 1 :
8800
Sample Input 2 :
Sample Output 2 :
9750
Sample Input 3 :
Sample Output 3 :
Invalid Input
Question-10
Problem Statement – 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.
Note : The input other than 4 digit positive number[includes negative and 0] is
considered as invalid.
Sample Input 1:
Lucky Number
Sample Input 2:
Question-11
Problem Statement –
Sample Input 1:
Enter no of course:
5
Oracle
C++
Mysql
Dotnet
Sample Output 1:
Sample Input 2:
Enter no of course:
3
Oracle
Dotnet
Sample Output 2:
Sample Input 3:
Enter no of course:
0
Sample Output 3:
Invalid Range
Question-12
Problem Statement – 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.
[Input Format: The first input refers to the no of items; the second input is the
item name, price and discount percentage separated by comma(,)]
Assume the minimum discount offer is in the form of Integer.
Note: There can be more than one product with a minimum discount.
Sample Input 1:
mobile,10000,20
shoe,5000,10
watch,6000,15
laptop,35000,5
Sample Output 1:
shoe
Explanation: The discount on the mobile is 2000, the discount on the shoe is 500,
the discount on the watch is 900 and the discount on the laptop is 1750. So the
discount on the shoe is the minimum.
Sample Input 2:
Mobile,5000,10
shoe,5000,10
WATCH,5000,10
Laptop,5000,10
Sample Output 2:
Mobile
shoe
WATCH
Laptop
Question-13
Problem Statement – 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.”
Sample Input 1:
Enter no of semester:
3
Sample Output 1:
Enter no of semester:
3
Sample Output 2:
Question-14
Problem Statement – 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. Write a class
FindFactor.java and write the main method in it.
Note :
If the input provided is negative, ignore the sign and provide the output. If the
input is zero
If the input is zero the output should be “No Factors”.
Sample Input 1 :
54
Sample Output 1 :
1, 2, 3, 6, 9, 18, 27, 54
Sample Input 2 :
-1869
Sample Output 2 :
Q1. Write a Python code to print the position or index of a given string (taken as
input from a user) from a given list of strings.
Q2. Make a function check_palindrome() that takes a list of strings as an argument.
It returns the string which is a palindrome.
Q3. Create a function count_words() which takes a string as input and creates a
dictionary with a word in the string as a key and its value as the number of times
the word is repeated in the string. It should return the dictionary.
eg: "hello hi hello world hello"
dict={'hello':3,'hi':1,'word':1}
Q4. Write a Python program to create a class called mobile which contains a method
called display which displays the name of the mobile owner, mobile brand, colour
and camera pixel.
Q5. Write a Python program to calculate the salary of the temporary staff using
Multilevel Inheritance.
Q6. Write a Python program to check the quantity of petrol in the bike using
exception handling.
Q7.Write a Python program to display the Passport details of the Person using
composition.
Q8. Longest Increasing Subsequence
Q9. Consider a row of n coins. We play a game against an opponent by alternative
turns. In each turn, a player selects either the first or last coin from the row.
Now remove it from the row permanently and take the value of a coin. Find the
maximum possible amount of money.
Q1. Write a Python code to print the position or index of a given string (taken as
input from a user) from a given list of strings.
Ans. The program will take input from the user in the form of a string and will
pass the string as an argument to a function. The function will take the strings as
arguments and return the Position(or index) of the list if the passed string is
present in the list, else it’ll return “String not found”. If the passed strings
are present at multiple indices, in that case, the function should only return The
first index of occurrence.
Considering the above scenario into account, build the logic to print the position
of the passed string from a given list of strings.
Refer to the below instructions and sample input-Output for more clarity on the
requirement.
Input:
abcd123Fghy
India
Progoti.c
India
Output:
def isPresent(lis,st):
if lis[i] == st:
return i
lis = []
for j in range(int(input())):
lis.append(input())
st = input()
ind = isPresent(lis,st)
if ind == -1:
else:
print(“Position of the searched string is: “,ind)
malayalam
radar
nitish
Output:
malayalam
radar
code:
def check_palindrome(lis):
palin_lis = []
for i in lis:
if i == i[::-1]:
palin_lis.append(i)
return palin_lis
lis = []
for i in range(int(input())):
lis.append(input())
for _ in check_palindrome(lis):
print(_)
Q3. Create a function count_words() which takes a string as input and creates a
dictionary with a word in the string as a key and its value as the number of times
the word is repeated in the string. It should return the dictionary.
eg: “hello hi hello world hello”
dict={‘hello’:3,’hi’:1,’word’:1}
Create another function max_accurance_word() which takes a string as input and
returns the word which is occurring a maximum number of times in the string. Use
the count_words function inside this function.
Sample input:
Sample output:
‘hello’
Code:
def count_words(string):
l=string.split()
s=set(l)
d={}
for i in s:
x=l.count(i)
d[i]=x
return d
def max_occurance(string):
d=count_words(string)
l1=[]
for i in d.values():
l1.append(i)
max1=max(l1)
for i in d.keys():
if d[i]==max1:
return i
string=input()
print(max_occurance(string))
Q4. Write a Python program to create a class called mobile which contains a method
called display which displays the name of the mobile owner, mobile brand, colour
and camera pixel.
Input Format:
Output Format:
Output is a String
Sample Input:
Dinesh
gold
13
Sample Output:
Dinesh’s own Lenovo vibe K5 note gold colour smartphone has a 13 MP camera
Case 1
Case 2
Input (stdin)
Dinesh
gold
13
Output (stdout)
Dinesh’s own Lenovo vibe K5 note gold colour smartphone has a 13 MP camera
Input (stdin)
Manoj
Vivo v11
white
21
Output (stdout)
Code:
class mobile:
def __init__(self,owner,brand,color,camera):
self.owner = owner
self.brand = brand
self.color = color
self.camera = camera
def display(self):
a= input()
b= input()
c= input()
d= input()
obj = mobile(a,b,c,d)
obj.display()
Q5. Write a Python program to calculate the salary of the temporary staff using
Multilevel Inheritance.
Description:
The method Salary(self) returns the total salary earned. The method display(self)
displays a number of days, hours worked and total salary earned.
Input Format:
Integer => Id
Output Format:
Sample Input:
Tilak
157934
20
Sample Output:
Staff Id is = 157934
No. of Days = 20
Case 1
Case 2
Input (stdin)
Tilak
157934
20
Output (stdout)
Staff Id is = 157934
No. of Days = 20
Input (stdin)
Praveen
124563
26
Output (stdout)
Staff Id is = 124563
No. of Days = 26
Code:
class employee:
def __init__(self,name,id,days,hours):
self.name = name
self.id = id
self.days = days
self.hours = hours
def display(self):
a = input()
b = int(input())
c = int(input())
d = int(input())
obj = employee(a,b,c,d)
obj.display()
Q6. Write a Python program to check the quantity of petrol in the bike using
exception handling.
If there is no petrol i.e. null in the bike it should raise an exception. That
exception is handled by using except block and it should print “There is no fuel in
the bike”. Otherwise, it should the show quantity of petrol on the bike.
Input Format:
Output Format:
Output is a String
Sample Input:
40
Sample Output:
Petrol Quantity = 40
Case 1
Case 2
Input (stdin)
40
Output (stdout)
Petrol Quantity = 40
Input (stdin)
NulL
Output (stdout)
Code:
a=input()
try:
if(a.lower()!=’null’):
else:
raise ValueError
except(ValueError) :
Q7.Write a Python program to display the Passport details of the Person using
composition.
Description:
Create a class Passport and class Person. Compose the class Passport in the class
Person.
Class Passport contains constructor __init__() which sets the name, address and
passport no.
Display the name of the person, Address and passport number of the person.
Input Format:
Output Format:
Sample Input:
RamKumar
Kollam
J7546891
Sample Output:
Name: RamKumar
Address: Kollam
Case 1
Case 2
Input (stdin)
RamKumar
Kollam
J7546891
Output (stdout)
Name: RamKumar
Address: Kollam
Input (stdin)
Purushothaman
Mumbai
J1535231
Output (stdout)
Name: Purushothaman
Address: Mumbai
class passport:
def __init__(self,name,address,pa):
self.name=name
self.address=address
self.pa=pa
def display(self):
print(“Name :”,self.name)
print(“Address :”,self.address)
class person(passport):
def __init__(self,name,address,pa):
super().__init__(name,address,pa)
super().display()
a=input()
b=input()
c=input()
e1=person(a,b,c)
Format:
Input:
The integer input is ‘n’. And Integer array ‘A’ input, contains ‘n’ integers.
Output:
Constraint:
Input:
1, 3, 2
Output:
Case 1
Case 2
Input (stdin)
1 3 2
Output (stdout)
Input (stdin)
10 22 9 33 21 50 41 60 80
Output (stdout)
Code:
def lis(arr,n):
lis = [1]*n
lis[i] = lis[j]+1
maximum = 0
for i in range(n):
return maximum
n=int(input())
arr = []
print(lis(arr,n))
Input:
5 3 7 10
Output:
15
Case 1
Case 2
Case 3
Case 6
Case 7
Case 8
Case 9
Case 10
Input (stdin)
5 3 7 10
Output (stdout)
15
Input (stdin)
8 15 3 7 10 22 5
Output (stdout)
26
Input (stdin)
10 3 8 2 6 7 15 1
Output (stdout)
39
Input (stdin)
1 2 3 4 5
Output (stdout)
Input (stdin)
11 22 33 44 55 66 88
Output (stdout)
187
Code:
for i in range(n)]
i = j – gap
x = 0
x = table[i + 2][j]
y = 0
y = table[i + 1][j – 1]
z = 0
z = table[i][j – 2]
return table[0][n – 1]
n=int(input())
print(optimalStrategyOfGame(arr1, n))