0% found this document useful (0 votes)
5 views

python scenario

The document outlines several Python programming challenges, including decoding a scrambled number, calculating pages read in a month with increasing daily goals, reversing lottery ticket numbers, determining prime numbers and their factorials, simulating a game with survival rounds, creating a study plan based on subjects and time left, and designing a treasure hunt game with specific rules. Each challenge includes test cases, explanations, and sample code to illustrate the solution. The document serves as a comprehensive guide for practicing Python programming through various scenarios.

Uploaded by

Amol Adhangale
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

python scenario

The document outlines several Python programming challenges, including decoding a scrambled number, calculating pages read in a month with increasing daily goals, reversing lottery ticket numbers, determining prime numbers and their factorials, simulating a game with survival rounds, creating a study plan based on subjects and time left, and designing a treasure hunt game with specific rules. Each challenge includes test cases, explanations, and sample code to illustrate the solution. The document serves as a comprehensive guide for practicing Python programming through various scenarios.

Uploaded by

Amol Adhangale
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 31

Secret Code Cracker

Secret Code Cracker Problem in Python


You’re a software engineer working on a special project to protect important
information. You’ve found a secret message, but it’s been scrambled by reversing
the digits of a 3-digit number. Your job is to figure out the original message by
reversing the digits back to how they were.To do this, write a Python program that
will decode the 3-digit message for you.
Test Case:
Input:
Encoded Number: 1234
Expected Output:
The decoded number is: 4321

Explanation:

The program asks you to enter the 3-digit encoded number.


It extracts the last digit of the number using the modulus operator (% 10).
Then it derives the middle digit by first dividing the number by 10 to remove the
last digit, then taking the modulus of the result with 10.
Now obtain the first digit by dividing the number by 100.
Afterward, it reconstructs the decoded number by placing the last digit in the
hundreds place, the middle digit in the tens place, and the first digit in the
units place.
Finally, the program displays the decoded number as the result.
Python
xxxxxxxxxx

# Taking input from the user


encoded_number = int(input("Enter the encoded 3-digit number: "))
# Extract each digit using modulus and integer division
digit1 = encoded_number % 10
digit2 = (encoded_number // 10) % 10
digit3 = (encoded_number // 100) % 10
# Reconstruct the reversed number
decoded_number = digit1 * 100 + digit2 * 10 + digit3
# Displaying the results
print(f"The decoded number is: {decoded_number}")

Book Reading Challenge


Book Reading Challenge Problems For loops in Python
You’ve set a goal to read a certain number of pages every day for a month, but you
plan to increase the number of pages you read each week. The first week, you read a
fixed number of pages every day. In the second week, you decide to read 5 more
pages each day compared to the previous week. In the third week, you decide to
increase it by another 5 pages per day, and so on for the entire month.Write a
Python program that calculates the number of pages you will read in a month based
on this increasing pattern.
Test Case:
Input:
Pages to read in the first week: 20
Days in a month: 30
Expected Output:
Total pages read: 1200

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

pages_per_day_first_week = int(input("Enter the number of pages you read per day in


the first week: "))
days_in_month = int(input("Enter the number of days in the month: "))
total_pages = 0
pages_per_day = pages_per_day_first_week
weeks_in_month = days_in_month // 7 # Calculate number of full weeks
remaining_days = days_in_month % 7 # Days left after full weeks
# Loop through each week
for week in range(1, weeks_in_month + 1):
total_pages += pages_per_day * 7 # Add pages read in each full week
pages_per_day += 5 # Increase pages per day by 5 for the next week
# Handle the remaining days in the last partial week
if remaining_days > 0:
total_pages += pages_per_day * remaining_days
print(f"Total pages read: {total_pages}")

Reversing a Lottery Ticket Number


Reversing a Lottery Ticket Number Loops in Python Problem
Imagine you are a lottery organizer. Each lottery ticket has a unique 3-digit
number, and you want to create a special reward code by reversing the digits of the
ticket number. For example, if the ticket number is 123, the reward code will be
321. This reversed number will be used to determine bonus prizes for the lucky
participants.How can you reverse the digits of a 3-digit lottery ticket number
using Python?
Test Case:
Input:
123
Expected Output:
The reversed reward code is: 321

Explanation:
This code reverses a 3-digit lottery ticket number and displays it as a “reward
code.”

The ticket_number variable is initialized by taking the user’s input, which is


converted into an integer using int().
The reversed_number variable is initialized to 0 and will store the reversed ticket
number as the digits are extracted.
A while loop runs as long as the ticket_number is greater than 0. Inside the loop,
the last digit of ticket_number is extracted using the modulus operator (% 10) and
stored in the variable digit.
The extracted digit is then added to reversed_number, but first, reversed_number is
multiplied by 10 to shift its digits left (making space for the new digit).
After adding the digit, the last digit is removed from ticket_number using integer
division (// 10).
The loop continues until all digits are reversed, and then the print() function
displays the final reversed reward code.
Python
xxxxxxxxxx

ticket_number = int(input("Enter a 3-digit lottery ticket number: "))


reversed_number = 0
while ticket_number > 0:
digit = ticket_number % 10 # Extract the last digit
reversed_number = reversed_number * 10 + digit # Add it to the reversed number
ticket_number //= 10 # Remove the last digit
print(f"The reversed reward code is: {reversed_number}")

A Rare Number Experiment


A Rare Number Experiment Probelm for loops in Python
In a mathematics research competition, participants are tasked with exploring
special numbers. For each number they select, they must determine whether it is a
prime number. If it is prime, they must find its factorial and count the total
digits in the factorial. This information will help the researchers understand the
relationship between prime numbers and the complexity of their factorials.Write a
Python program to determine if a number is prime, calculate its factorial if it is
prime, and count the total digits in the factorial.
Test Cases
Input:
Enter a number: 7
Expected Output:
7 is a prime number.
Factorial of 7 is 5040.
Total digits in the factorial: 4.

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

number = int(input("Enter a number: "))


is_prime = True
factorial = 1
digits = 0
for i in range(1, number + 1):
# Check for primality (only runs for numbers greater than 1)
if i > 1 and number % i == 0 and i != number:
is_prime = False

# 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}.")

# Count digits in the factorial


factorial_str = str(factorial)
digits = len(factorial_str)

print(f"Total digits in the factorial: {digits}.")


else:
print(f"{number} is not a prime number.")

The Squid Game Round


The Squid Game Round Problem for loops in Python
Imagine you’re a contestant in a tough round of Squid Game. In this game, you start
with a number, and in each round, the number changes. Sometimes, it gets bigger by
multiplying by 2, or it gets bigger by adding a certain value. If the number ever
has the digit “7” in it, you lose and the game ends. But if the number is divisible
by 4, you get a second chance, and the number will be cut in half. Your job is to
see how many rounds you can survive before the number breaks the rules, and count
the total rounds it takes for the game to end. Write a Python program that
simulates the game and tells you if you survive each round or not.
Test Case:
Input:
Enter the starting number: 5
Enter the number of rounds: 6
Expected Output:
Round 1: You survive with the number 8.
Round 2: The number 16 was divisible by 4, halved!
Round 3: You survive with the number 13.
Round 4: You survive with the number 26.
Round 5: The number 52 was divisible by 4, halved!
Round 6: You survive with the number 20.

You survived 6 rounds before failing!

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

initial_number = int(input("Enter the starting number: "))


rounds = int(input("Enter the number of rounds: "))
count_rounds = 0
for round_num in range(1, rounds + 1):
number = initial_number

if round_num % 2 == 0:
number *= 2
else:
number += 3

# Check if the number contains '7'


if '7' in str(number):
print(f"Round {round_num}: The number {number} contains '7'. You lose!")
break #the game ends
# Check if the number is divisible by 4
if number % 4 == 0:
number = number // 2
print(f"Round {round_num}: The number {number} was divisible by 4,
halved!")
else:
print(f"Round {round_num}: You survive with the number {number}.")
count_rounds += 1 # Increment rounds survived
print(f"\nYou survived {count_rounds} rounds before failing!")

Study Plan for Exams


Study Plan for Exams Nested if-else Python Problem
You wake up in a panic.your PEM exams are way closer than you expected! You grab
your phone and open a study app to figure out how to prepare in the little time you
have. The app asks for two things: your subject and how much time is left. Based on
your answers, it gives a study plan:
If your subject is Python:If you have less than a week, focus on Practice
Problems.Otherwise, review the main Concepts.
If your subject is MySql:
If you have more than a week, make Detailed Notes.Otherwise, focus on Memorizing
key points.
For any other subject:
If you have more than a week, do a Thorough Study.Otherwise, do a Quick Revision.
Write a Python program to implement this logic and suggest a study plan.
Test Case:
Input:
Subject: python
Time: More than a week
Expected Output:
Suggested Plan: Detailed Notes.
Explanation:
This program helps suggest a study plan based on the user’s chosen subject and the
amount of time left for preparation.

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

subject = input("Enter your subject (Math/History/Other): ")


time = input("How much time is left (Less than a week/More than a week)? ")
if subject == "Math":
if time == "Less than a week":
print("Suggested Plan: Practice Problems.")
else:
print("Suggested Plan: Concept Reviews.")
elif subject == "History":
if time == "More than a week":
print("Suggested Plan: Detailed Notes.")
else:
print("Suggested Plan: Memorization Techniques.")
else:
if time == "More than a week":
print("Suggested Plan: Thorough Study.")
else:
print("Suggested Plan: Quick Revision.")

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”.

[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.]

The result should be with two decimal place.To get two decimal place refer the
below-mentioned print statement :

float cost=670.23;

System.out.printf(“You need a sum of Rs.%.2f to cover the trip”,cost);

Sample Input 1:

Enter the no of liters to fill the tank


20

Enter the distance covered


150

Sample Output 1:

Liters/100KM
13.33

Miles/gallons
17.64

Explanation:

For 150 KM fuel consumption is 20 liters,


Then for 100 KM fuel consumption would be (20/150)*100=13.33,
Distance is given in KM, we have to convert it to miles (150*0.6214)=93.21,
Fuel consumption is given in liters, we have to convert it to gallons
(20*0.2642)=5.284,
Then find (miles/gallons)=(93.21/5.284)=17.64
Sample Input 2:

Enter the no of liters to fill the tank


-5

Sample Output 2:

-5 is an Invalid Input
Sample Input 3:

Enter the no of liters to fill the tank


25

Enter the distance covered


-21

Sample Output 3:

-21 is an Invalid Input

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:

Enter the no of pizzas bought:10


Enter the no of puffs bought:12
Enter the no of cool drinks bought:5
Sample Output 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:

Enter the digits:


65
66
67
68
Sample Output 1:

65-A
66-B
67-C
68-D

Sample Input 2:

Enter the digits:


115
116
101
112
Sample Output 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:

Enter the no of students placed in CSE:90


Enter the no of students placed in ECE:45
Enter the no of students placed in MECH:70
Sample Output 1:

Highest placement
CSE

Sample Input 2:

Enter the no of students placed in CSE:55


Enter the no of students placed in ECE:85
Enter the no of students placed in MECH:85
Sample Output 2:

Highest placement
ECE

MECH

Sample Input 3:

Enter the no of students placed in CSE:0


Enter the no of students placed in ECE:0
Enter the no of students placed in MECH:0
Sample Output 3:

None of the department has got the highest placement


Sample Input 4:

Enter the no of students placed in CSE:10


Enter the no of students placed in ECE:-50
Enter the no of students placed in MECH:40
Sample Output 4:

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:

Enter the no of ticket:35


Do you want refreshment:y
Do you have coupon code:y
Enter the circle:k
Sample Output 1:

Ticket cost:4065.25
Sample Input 2:

Enter the no of ticket:1


Sample Output 2:

Minimum of 5 and Maximum of 40 Tickets

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.

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”.

Sample Input 1:

Enter the month:11


Sample Output 1:

Season:Autumn
Sample Input 2:

Enter the month:13


Sample Output 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:

Provide valid input

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.

Note : If either the salary is 0 or negative (or) if the appraisal rating is


not in the range 1 to 5 (inclusive), then the output should be “Invalid Input”.

Sample Input 1 :

Enter the salary


8000
Enter the Performance appraisal rating
3

Sample Output 1 :

8800

Sample Input 2 :

Enter the salary


7500

Enter the Performance appraisal rating


4.3

Sample Output 2 :

9750

Sample Input 3 :

Enter the salary


-5000

Enter the Performance appraisal rating


6

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.

Refer the samples, to read and display the data.

Sample Input 1:

Enter the car no:1234


Sample Output 1:

Lucky Number
Sample Input 2:

Enter the car no:1214


Sample Output 2:

Sorry its not my lucky number


Sample Input 3:

Enter the car no:14


Sample Output 3:
14 is not a valid car number

Question-11
Problem Statement –

IIHM institution is offering a variety of courses to students. Students have a


facility to check whether a particular course is available in the institution.
Write a program to help the institution accomplish this task. If the number is less
than or equal to zero display “Invalid Range”.

Assume maximum number of courses is 20.

Sample Input 1:

Enter no of course:
5

Enter course names:


Java

Oracle

C++

Mysql

Dotnet

Enter the course to be searched:


C++

Sample Output 1:

C++ course is available

Sample Input 2:

Enter no of course:
3

Enter course names:


Java

Oracle

Dotnet

Enter the course to be searched:


C++

Sample Output 2:

C++ course is not available

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

Enter no of subjects in 1 semester:


3

Enter no of subjects in 2 semester:


4

Enter no of subjects in 3 semester:


2

Marks obtained in semester 1:


50
60
70

Marks obtained in semester 2:


90
98
76
67

Marks obtained in semester 3:


89
76

Sample Output 1:

Maximum mark in 1 semester:70


Maximum mark in 2 semester:98
Maximum mark in 3 semester:89
Sample Input 2:

Enter no of semester:
3

Enter no of subjects in 1 semester:


3

Enter no of subjects in 2 semester:


4

Enter no of subjects in 3 semester:


2

Marks obtained in semester 1:


55
67
98
Marks obtained in semester 2:
67
-98

Sample Output 2:

You have entered invalid mark.

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 :

1, 3, 7, 21, 89, 267, 623, 1869

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:

Hello Good Morning

abcd123Fghy

India

Progoti.c

India

Output:

The position of the searched string is: 2

def isPresent(lis,st):

for i in range(0, len(lis)):

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:

print(“String not found”)

else:
print(“Position of the searched string is: “,ind)

Q2. Make a function check_palindrome() that takes a list of strings as an argument.


It returns the string which is a palindrome.
Input:

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:

“hello hi hello world hello”

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:

String => name

String => brand name

String => color

Integer => pixel

Output Format:

Output is a String
Sample Input:

Dinesh

Lenovo vibe K5 note

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

Lenovo vibe K5 note

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)

Manoj own Vivo v11 white colour smartphone having a 21 MP camera

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):

print(“{owner} own {brand} {color} color smartphone having {camera} MP


camera”.format(owner = self.owner,brand = self.brand,color = self.color,camera =
self.camera))

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:

Create a class Person which contains a constructor __init__() and a method


display(self). The method displays the name of the person

Create another class Staff which inherits Person. It contains a constructor


__init__() and a method display(self). The method displays Id.

Create another class Temporarystaff which inherits Staff, it also contains a


constructor __init__() and two method displays (self), and Salary(self).

The method Salary(self) returns the total salary earned. The method display(self)
displays a number of days, hours worked and total salary earned.

salary earned = total hours worked *150

Input Format:

String => name

Integer => Id

Integer => number of days

Integer => hoursworked

Output Format:

All outputs contain strings and integers.

Sample Input:

Tilak

157934
20

Sample Output:

Name of Person = Tilak

Staff Id is = 157934

No. of Days = 20

No. of Hours Worked = 8

Total Salary = 24000

Case 1

Case 2

Input (stdin)

Tilak

157934

20

Output (stdout)

Name of Person = Tilak

Staff Id is = 157934

No. of Days = 20

No. of Hours Worked = 8

Total Salary = 24000

Input (stdin)

Praveen

124563

26

Output (stdout)

Name of Person = Praveen

Staff Id is = 124563
No. of Days = 26

No. of Hours Worked = 6

Total Salary = 23400

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):

print(“Name of Person = {name}\nStaff Id is = {id}\nNo. of Days = {days}\nNo.


of Hours Worked = {hours}\nTotal Salary =
{salary}”.format(name=self.name,id=self.id,days=self.days,hours=self.hours,salary=s
elf.days*self.hours*150))

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:

The input consists of a string which denotes a fuel.

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)

There is no fuel in the Bike

Code:

a=input()

try:

if(a.lower()!=’null’):

print(“Petrol Quantity = “,a)

else:

raise ValueError

except(ValueError) :

print(“There is no fuel in the Bike”)

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:

Name => String

Address => String


passport number => String

Output Format:

Three outputs. All are String

Sample Input:

RamKumar

Kollam

J7546891

Sample Output:

Name: RamKumar

Address: Kollam

Passport Number: J7546891

Case 1

Case 2

Input (stdin)

RamKumar

Kollam

J7546891

Output (stdout)

Name: RamKumar

Address: Kollam

Passport Number: J7546891

Input (stdin)

Purushothaman

Mumbai

J1535231

Output (stdout)

Name: Purushothaman

Address: Mumbai

Passport Number: J1535231


Code:

#Type your code here…

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)

print(“Passport Number :”,self.pa)

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)

Q8. Longest Increasing Subsequence


Given an integer array ‘A’. Find the length of its Longest Increasing Subsequence
of a sub-array from the given integer array. The elements are sorted in monotonic
increasing order. You need to create a function that takes two inputs – integer ‘n’
and an integer array containing ‘n’ integers. To return the length of its LIS.

Format:

Input:

The integer input is ‘n’. And Integer array ‘A’ input, contains ‘n’ integers.

Output:

Return the length of its LIS.

Constraint:

1 <= input1 <= 1000


Example:

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

for i in range (1, n):

for j in range(0 , i):

if arr[i] > arr[j] and lis[i]< lis[j] + 1 :

lis[i] = lis[j]+1

maximum = 0

for i in range(n):

maximum = max(maximum , lis[i])

return maximum
n=int(input())

arr = []

arr=list(map(int, input().split(‘ ‘)[:n]))

print(lis(arr,n))

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.
Example:

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:

def optimalStrategyOfGame(arr, n):

table = [[0 for i in range(n)]

for i in range(n)]

for gap in range(n):

for j in range(gap, n):

i = j – gap

x = 0

if((i + 2) <= j):

x = table[i + 2][j]

y = 0

if((i + 1) <= (j – 1)):

y = table[i + 1][j – 1]
z = 0

if(i <= (j – 2)):

z = table[i][j – 2]

table[i][j] = max(arr[i] + min(x, y),

arr[j] + min(y, z))

return table[0][n – 1]

n=int(input())

arr1 = [int(i) for i in input().split()]

print(optimalStrategyOfGame(arr1, n))

You might also like