UNIT-1
1. Basic Programs.
a. Adding Two Numbers
[Link]
Problem Statement
Your task is very simple: given two integers A and B, write a program to add these two
numbers and output the sum.
Input Format
● The first line contains an integer T, the total number of test cases.
● Then follow T lines, each line contains two integers, A and B.
Output Format
For each test case, add A and B and display the sum in a new line.
Constraints
● 1≤T≤1000
● 0≤A,B≤10000
Sample 1:
Input
3
1 2
100 200
10 40
Output
3
300
50
Explanation:
Testcase 1: 1+2=3. Hence the first output is 3.
Testcase 2: 100+200=300. Hence the second output is 300.
Program :
t = int(input())
for i in range(0,t):
a,b = map(int,input().split())
print(a+b)
1
b. Perfect Square root or not
[Link]
Program Description
Find out given number has a perfect square root or not
Any number which can be expressed as the product of two whole equal numbers is classified
as a perfect square. For example, 64 can be written as 8*8 hence 64 is a perfect square.
Input Format
Single line contains an integer n
Output Format
Display whether given number is a perfect square or not.
Constraints
0<=n<=100000
Explanation
Testcase 2 :
36 = 6*6 so it is perfect square
Input-1
26
Output-1
False
Input-2
36
Output-2
True
Program :
n = int(input())
i = 0
while(i*i<n):
i += 1
if(i*i==n):
print("True")
else:
print("False")
2
c. Perfect Number
[Link]
Program Description
We define the Perfect Number is a positive integer that is equal to the sum of all its positive
divisors except itself.
Now, given an integer n, write a function that returns true when it is a perfect number and false
when it is not.
Input Format
A single lline input containing one integer.
Output Format
Print the output according to the description.
Constraints
0<=n<=100000
Explanation
Testcase 2 :
28 = 1 + 2 + 4 + 7 + 14
Input-1
10
Output-1
False
Input-2
28
Output-2
True
Program :
n = int(input())
sum = 0
for i in range(1,n):
if(n%i==0):
sum = sum + i
if(sum==n):
print("True")
else:
print("False")
3
d. Even Number or Odd number
[Link]
Task
Given an integer, , perform the following conditional actions:
● If is odd, print Weird
● If is even and in the inclusive range of to , print Not Weird
● If is even and in the inclusive range of to , print Weird
● If is even and greater than , print Not Weird
Input Format
A single line containing a positive integer, .
Constraints
1<=n<=100
Output Format
Print Weird if the number is weird. Otherwise, print Not Weird.
Sample Input 0
3
Sample Output 0
Weird
Explanation 0
n=3
n is odd and odd numbers are weird, so print Weird.
Sample Input 1
24
Sample Output 1
Not Weird
4
Explanation 1
n = 24
n>20 and is even, so it is not weird
Program :
n = int(input())
if(n%2==0):
if(n>=2 and n<=5) :
print("Not Weird")
elif(n>=6 and n<=20) :
print("Weird")
else:
print("Not Weird")
else:
print("Weird")
5
2. Decision Structures and Loops.
a. Python Loops – Printing Squares of Numbers
[Link]
Task
The provided code stub reads an integer, , from STDIN. For all non-negative integers , print .
Example
The list of non-negative integers that are less than is . Print the square of each number on a
separate line.
0
1
4
Input Format
The first and only line contains the integer, .
Constraints
Output Format
Print lines, one corresponding to each .
Sample Input 0
5
Sample Output 0
0
1
4
9
16
Program :
n = int(input())
for i in range(0, n):
print(i**2)
6
b. Check for Armstrong number, Palindrome.
[Link]
submissions/code/1406993984
Problem Statement
An Armstrong number of three digits is an integer such that the sum of the cubes of its digits
is equal to the number itself. Write a program to test whether a given number is an Armstrong
number or not.
Input Format
First line consists of an integer T which is the number of [Link] then there will be T
line-separated numbers each line consisting of a single integer N.
Constraints
1 < N < 999
Output Format
T number of line separted strings,each line consisting of a string "Yes",if N is an armstrong
number and "No",if N isn't an armstrong number.
Sample Input
3
345
0
Sample Output
No
Yes
Yes
Explanation
3^3 + 4^3 + 5^3 is not equal to [Link] 345 isn't an armstrong number. 1^3 = [Link] 1 is
an armstrong number. 0^3 = [Link] 0 is an armstrong number.
Program :
T = int(input())
for i in range(T):
N = int(input())
temp = N
arm_strong = 0
while(temp!=0):
r = temp%10
arm_strong = arm_strong + r ** 3
7
temp = temp//10
if (N==arm_strong):
print("Yes")
else:
print("No")
c. Spy Number
[Link]
Program Description
Write A Program to check the given number is spy number or not, and display messages Spy
Number or Not Spy Number.
Spy Number-A Number is spy number, if the sum of its digits equals the product of its digits.
Input Format
A single line input contains an integer N.
Output Format
Print the output according to the description.
Constraints
1<=N<=104
Explanation
Input 1:
Consider the number = 1124
Sum of the digits = 1 + 1 + 2 + 4
Product of the digits = 1 * 1 * 2 * 4
Input-1
1124
Output-1
Spy Number.
Program :
N = int(input())
sum = 0
prod = 1
while(N!=0) :
8
rem = N % 10
sum = sum + rem
prod = prod * rem
N = N // 10
if(sum == prod):
print("Spy Number")
else:
print("Not Spy Number")
d. Compound Interest
[Link]
Program Description
Given a principle amount , time and rate of interset . Find the Total Amount using Compound
interest .
Input Format
P,R,T - principle amount , rate of interest , time .
Output Format
Total Amount. ( print upto two decimal values )
Constraints
1<=P,R,T<=104
Input-1
10 20 30
Output-1
2373.76
Input-2
1110 2 6
Output-2
1250.04
Program :
P, R, T = map(float, input().split())
A = P * (1 + R/100) ** T
print(f"{A:.2f}")
9
e. Count vowels, consonants, digits in a string.
[Link]
Problem Statement
Chef has a string S with length N. He needs to find the number of indices i (1≤i≤N−1) such that
the i-th character of this string is a consonant and the i+1-th character is a vowel. However, he
is busy, so he asks for your help.
Note: The letters 'a', 'e', 'i', 'o', 'u' are vowels; all other lowercase English letters are consonants.
Input
● The first line of the input contains a single integer T denoting the number of test
cases. The description of T test cases follows.
● The first line of each test case contains a single integer N.
● The second line contains a single string S with length N.
Output
For each test case, print a single line containing one integer ― the number of occurrences of a
vowel immediately after a consonant.
Constraints
● 1≤T≤100
● 1≤N≤100
● S contains only lowercase English letters
Subtasks
Subtask #1 (100 points): original constraints
Sample 1:
Input
3
6
bazeci
3
abu
1
o
Output
3
1
0
Explanation:
Example case 1: The vowel 'a' follows after the consonant 'b', 'e' follows after 'z' and 'i' follows
after 'c', so the answer is 3.
10
Example case 2: The only vowel 'u' follows after 'b', so the answer is 1.
Program :
t = int(input())
vowels = "aeiou"
for _ in range(t):
n = int(input())
s = input()
count = 0
for i in range(n - 1):
if (s[i] not in vowels and s[i + 1] in vowels):
count += 1
print(count)
11
f. Print a number pyramid.
[Link]
CodeMaster is trying to solve pattern problem. Codemaster has given N to create a pattern.
Help the CodeMaster to code this pattern problem.
Pattern01
Input:
Problem Statement
● First line will contain T, number of testcases.
● Each testcase contains of a single line of input,one integers N.
Output:
For each testcase, output as the pattern.
Constraints
● 1≤T≤10
● 1≤N≤15
Sample Input:
2
3
4
Sample Output:
A65
ABA656665
AABAA6565666565
A65
ABA656665
AABAA6565666565
AAABAAA65656566656565
Program :
import sys
def main():
try:
data = [Link]().decode()
tokens = [Link]()
if not tokens:
[Link](0)
idx = 0
T = int(tokens[idx])
idx += 1
out = []
for _ in range(T):
if idx >= len(tokens):
break
N = int(tokens[idx])
idx += 1
for i in range(1, N + 1):
if i == 1:
letters = "A"
numbers = "65"
else:
letters = "A" * (i - 1) + "B" + "A" * (i - 1)
numbers = "65" * (i - 1) + "66" + "65" * (i - 1)
line = " " * (i - 1) + letters + numbers
[Link](line)
print("\n".join(out))
except Exception:
[Link](0)
main()
UNIT – II
Python Data Types:
a. String Matching in an Array
[Link]
Problem Statement
Given an array of string words, return all strings in words that are a of another word. You can
return the answer in any order.
Example 1:
Input: words = ["mass","as","hero","superhero"]
Output: ["as","hero"]
Explanation: "as" is substring of "mass" and "hero" is substring of "superhero".
["hero","as"] is also a valid answer.
Example 2:
Input: words = ["leetcode","et","code"]
Output: ["et","code"]
Explanation: "et", "code" are substring of "leetcode".
Example 3:
Input: words = ["blue","green","bu"]
Output: []
Explanation: No string of words is substring of another string.
Constraints:
● 1 <= [Link] <= 100
● 1 <= words[i].length <= 30
● words[i] contains only lowercase English letters.
● All the strings of words are unique.
Program :
class Solution:
def stringMatching(self, words):
result = []
for i in range(len(words)):
for j in range(len(words)):
if i != j and words[i] in words[j]:
[Link](words[i])
break
return result
b. Product-of-Three-Numbers
[Link]
1971863541
Problem Statement
Given an integer array nums, find three numbers whose product is maximum and return the
maximum product.
Example 1:
Input: nums = [1,2,3]
Output: 6
Example 2:
Input: nums = [1,2,3,4]
Output: 24
Example 3:
Input: nums = [-1,-2,-3]
Output: -6
Constraints:
● 3 <= [Link] <= 104
● -1000 <= nums[i] <= 1000
Program :
class Solution:
def maximumProduct(self, nums):
[Link]()
return max(nums[-1] * nums[-2] * nums[-3], nums[0] * nums[1] * nums[-1])
c. Write a program to check if the substring is present in a given string or not
[Link]
Problem Statement
In this challenge, the user enters a string and a substring. You have to print the number of
times that the substring occurs in the given string. String traversal will take place from left to
right, not from right to left.
NOTE: String letters are case-sensitive.
Input Format
The first line of input contains the original string. The next line contains the substring.
Constraints
Each character in the string is an ascii character.
Output Format
Output the integer number indicating the total number of occurrences of the substring in the
original string.
Sample Input
ABCDCDC
CDC
Sample Output
2
Concept
There are a couple of new concepts:
In Python, the length of a string is found by the function len(s), where is the string.
To traverse through the length of a string, use a for loop:
for i in range(0, len(s)):
print (s[i])
A range function is used to loop over some length:
range (0, 5)
Here, the range loops over to . is excluded.
Constraints
Program :
def count_substring(string, sub_string):
count = 0
for i in range(len(string) - len(sub_string) + 1):
if string[i:i+len(sub_string)] == sub_string:
count += 1
return count
string = input().strip()
sub_string = input().strip()
print(count_substring(string, sub_string))
d. Reverse-vowels-of-a-String
[Link]
Problem Statement
Given a string s, reverse only all the vowels in the string and return it.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more
than once.
Example 1:
Input: s = "IceCreAm"
Output: "AceCreIm"
Explanation:
The vowels in s are ['I', 'e', 'e', 'A']. On reversing the vowels, s becomes "AceCreIm".
Example 2:
Input: s = "leetcode"
Output: "leotcede"
Constraints:
● 1 <= [Link] <= 3 * 105
● s consist of printable ASCII characters.
Program :
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = set('aeiouAEIOU')
s = list(s)
left, right = 0, len(s) - 1
while left < right:
while left < right and s[left] not in vowels:
left += 1
while left < right and s[right] not in vowels:
right -= 1
if left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
return ''.join(s)
Lists, Tuples, Dictionary
a. Generate 20 random numbers; print min, max, avg, even count.
Program
a. Find Remainder
[Link]
Write a program to find the remainder when an integer A is divided by an integer B.
Input
The first line contains an integer T, the total number of test cases. Then T lines follow, each
line contains two Integers A and B.
Output
For each test case, find the remainder when A is divided by B, and display it in a new line.
Constraints
● 1 ≤ T ≤ 1000
● 1 ≤ A,B ≤ 10000
Sample 1:
Input
3
1 2
100 200
40 15
Output
1
100
10
b. Longest Consecutive Sequence
[Link]
Problem Statement
Given an unsorted array of integers nums, return the length of the longest consecutive
elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
Example 3:
Input: nums = [1,0,1,2]
Output: 3
Constraints:
● 0 <= [Link] <= 105
● -109 <= nums[i] <= 109
Program :
class Solution:
def longestConsecutive(self, nums):
num_set = set(nums)
best = 0
for n in num_set:
if n - 1 not in num_set:
length = 1
while n + length in num_set:
length += 1
best = max(best, length)
return best
c. Subarray Sum Equals K
[Link]
Problem Statement
Given an array of integers nums and an integer k, return the total number of subarrays whose
sum equals to k.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,1,1], k = 2
Output: 2
Example 2:
Input: nums = [1,2,3], k = 3
Output: 2
Constraints:
● 1 <= [Link] <= 2 * 104
● -1000 <= nums[i] <= 1000
● -107 <= k <= 107
Program :
class Solution:
def subarraySum(self, nums, k):
count = 0
prefix = 0
freq = {0: 1}
for n in nums:
prefix += n
if prefix - k in freq:
count += freq[prefix - k]
freq[prefix] = [Link](prefix, 0) + 1
return count
UNIT – III
1. Working with Function
a. Write a Python program to define a function that takes parameters and returns
the sum of two numbers.
[Link]
recursion/
Problem Statement:
Write a Python program that defines a function to add two numbers. The function should take
two integers as arguments and return their sum. The program should call this function with
different values and display the results.
Input:
The inputs are directly provided in the function calls within the program.
Output:
The program prints the sum of the given pairs of numbers.
Test Case 1:
Input:
3 5
Output:
8
Test Case 2:
Input:
10 20
Output:
30
Program :
def add(a, b):
return a + b
print(add(3, 5))
print(add(10, 20))
b. Two Sum — a classic easy problem that’s often solved using a function.
[Link]
Problem Statement
Given an array of integers nums and an integer target, return indices of the two numbers such
that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the
same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
● 2 <= [Link] <= 104
● -109 <= nums[i] <= 109
● -109 <= target <= 109
● Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
Program :
class Solution:
def twoSum(self, nums, target):
seen = {}
for i, n in enumerate(nums):
diff = target - n
if diff in seen:
return [seen[diff], i]
seen[n] = i
c. Valid Anagram — good practice for string/dictionary manipulations inside a
function.
[Link]
Problem Statement
Given two strings s and t, return true if t is an of s, and false otherwise.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Constraints:
● 1 <= [Link], [Link] <= 5 * 104
● s and t consist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution
to such a case?
Program :
class Solution:
def isAnagram(self, s, t):
if len(s) != len(t):
return False
count = {}
for c in s:
count[c] = [Link](c, 0) + 1
for c in t:
if c not in count:
return False
count[c] -= 1
if count[c] < 0:
return False
return True
d. FLOW001 — “Add Two Numbers”: simplest problem, good for writing a function to
sum two
[Link]
Problem Statement
Your task is very simple: given two integers A and B, write a program to add these two
numbers and output the sum.
Input Format
● The first line contains an integer T, the total number of test cases.
● Then follow T lines, each line contains two integers, A and B.
Output Format
For each test case, add A and B and display the sum in a new line.
Constraints
● 1≤T≤1000
● 0≤A,B≤10000
Sample 1:
Input
3
1 2
100 200
10 40
Output
3
300
50
Explanation:
Testcase 1: 1+2=3. Hence the first output is 3.
Testcase 2: 100+200=300. Hence the second output is 300.
Program :
t = int(input())
for i in range(0,t):
a,b = map(int,input().split())
print(a+b)
e. FLOW002 — “Compute the Average”: practice writing a function to compute
averages.
[Link]
Find Remainder
Problem Statement
Write a program to find the remainder when an integer A is divided by an integer B.
Input
The first line contains an integer T, the total number of test cases. Then T lines follow, each
line contains two Integers A and B.
Output
For each test case, find the remainder when A is divided by B, and display it in a new line.
Constraints
● 1 ≤ T ≤ 1000
● 1 ≤ A,B ≤ 10000
Sample 1:
Input
3
1 2
100 200
40 15
Output
1
100
10
Program :
t = int(input())
for i in range(t):
a, b = map(int, input().split())
print(a % b)
UNIT – IV
1. OOP – Classes and Methods
a. Create a Product class with dynamic pricing and stock update.
[Link]
Problem Statement
Chef and Street Food
Read problem statements in Hindi, Bengali, Mandarin Chinese, Russian, and Vietnamese as
well.
in Chefland, there is a very famous street where N types of street food (numbered 1 through N)
are offered. For each valid i, there are Si stores that offer food of the i-th type, the price of one
piece of food of this type is Vi (the same in each of these stores) and each day, Pi people
come to buy it; each of these people wants to buy one piece of food of the i-th type.
Chef is planning to open a new store at this street, where he would offer food of one of these
N types. Chef assumes that the people who want to buy the type of food he'd offer will split
equally among all stores that offer it, and if this is impossible, i.e. the number of these people
p is not divisible by the number of these stores s, then only sp people will buy food from
Chef.
Chef wants to maximise his daily profit. Help Chef choose which type of food to offer and find
the maximum daily profit he can make.
Input
● The first line of the input contains a single integer T denoting the number of test
cases. The description of T test cases follows.
● The first line of each test case contains a single integer N.
● N lines follow. For each i (1≤i≤N), the i-th of these lines contains three space-separated
integers Si, Pi and Vi.
Output
For each test case, print a single line containing one integer ― the maximum profit.
Constraints
● 1≤T≤100
● 1≤N≤100
● 1≤Si,Vi,Pi≤10,000 for each valid i
Subtasks
Subtask #1 (100 points): original constraints
Sample 1:
Input
2
3
4 6 8
2 6 6
1 4 3
1
7 7 4
Output
12
0
Explanation:
Example case 1: Chef should offer food of the second type. On each day, two people would
buy from him, so his daily profit would be 12.
Example case 2: Chef has no option other than to offer the only type of food, but he does not
expect anyone to buy from him anyway, so his daily profit is 0.
Program :
T = int(input())
for _ in range(T):
N = int(input())
max_profit = 0
for i in range(N):
S, P, V = map(int, input().split())
profit = (P // (S + 1)) * V
max_profit = max(max_profit, profit)
print(max_profit)
b. Define Converter class for unit conversions (e.g., inches feet).
[Link]
Translate
c. Create a Time class to convert seconds minutes, hours.
[Link]
Problem Statement:
Write a Python program that defines a class Time to represent time in seconds. The class
should include methods to convert the given time into minutes and hours.
● The constructor should initialize the time in seconds.
● A method to_minutes() should convert seconds into minutes.
● A method to_hours() should convert seconds into hours.
Create an object of the class and display the converted values.
Input:
The input (time in seconds) is directly provided while creating the object in the program.
Output:
The program prints:
● Time in minutes
● Time in hours
Test Cases:
Test Case 1:
Input:
7200
Output:
120.0
2.0
Test Case 2:
Input:
3600
Output:
60.0
1.0
Program :
class Time:
def __init__(self, seconds):
[Link] = seconds
def to_minutes(self):
return [Link] / 60
def to_hours(self):
return [Link] / 3600
t = Time(7200)
print(t.to_minutes())
print(t.to_hours())
2. File Handling
a. Say "Hello, World!" from a file (read input from file, print output):
[Link]
Problem Statement
An extra day is added to the calendar almost every four years as February 29, and the day is
called a leap day. It corrects the calendar for the fact that our planet takes approximately
365.25 days to orbit the sun. A leap year contains a leap day.
In the Gregorian calendar, three conditions are used to identify leap years:
● The year can be evenly divided by 4, is a leap year, unless:
● The year can be evenly divided by 100, it is NOT a leap year, unless:
● The year is also evenly divisible by 400. Then it is a leap year.
This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while
1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. Source
Task
Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True,
otherwise return False.
Note that the code stub provided reads from STDIN and passes arguments to the is_leap
function. It is only necessary to complete the is_leap function.
Input Format
Read
, the year to test.
Constraints
Output Format
The function must return a Boolean value (True/False). Output is handled by the provided
code stub.
Sample Input 0
1990
Sample Output 0
False
Explanation 0
1990 is not a multiple of 4 hence it's not a leap year.
Program :
def is_leap(year):
leap = False
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
return leap
year = int(input())
print(is_leap(year))
b. Reading from STDIN / file and processing lines:
[Link]
Problem Statement
You are given the firstname and lastname of a person on two different lines. Your task is to
read them and print the following:
Hello firstname lastname! You just delved into python.
Function Description
Complete the print_full_name function in the editor below.
print_full_name has the following parameters:
● string first: the first name
● string last: the last name
Prints
● string: 'Hello
! You just delved into python' where and are replaced with and .
Input Format
The first line contains the first name, and the second line contains the last name.
Constraints
The length of the first and last names are each ≤ .
Sample Input 0
Ross
Taylor
Sample Output 0
Hello Ross Taylor! You just delved into python.
Explanation 0
The input read by the program is stored as a string data type. A string is a collection of
characters.
Program :
def print_full_name(first, last):
print(f"Hello {first} {last}! You just delved into python.")
if __name__ == '__main__':
first_name = input()
last_name = input()
print_full_name(first_name, last_name)
c. FLOW001 – Add Two Numbers:
[Link]
Add Two Numbers
Your task is very simple: given two integers A and B, write a program to add these two
numbers and output the sum.
Input Format
● The first line contains an integer T, the total number of test cases.
● Then follow T lines, each line contains two integers, A and B.
Output Format
For each test case, add A and B and display the sum in a new line.
Constraints
● 1≤T≤1000
● 0≤A,B≤10000
Sample 1:
Input
3
1 2
100 200
10 40
Output
3
300
50
Explanation:
Testcase 1: 1+2=3. Hence the first output is 3.
Testcase 2: 100+200=300. Hence the second output is 300.
Program :
t = int(input())
for i in range(0,t):
a,b = map(int,input().split())
print(a+b)
UNIT – V
1. GUI and Exceptions
a. Build a file-open dialog and display content in a text box.
[Link]
Problem Statement
404 Not Found
Chef's website has a specific response mechanism based on the HTTP status code received:
● If the response code is 404, the website will return NOT FOUND.
● For any other response code different from 404, the website will return FOUND.
Given the response code as X, determine the website response.
Input Format
● The first and only line of input contains a response code X.
Output Format
Output on a new line NOT FOUND, if the response code is 404. Otherwise print FOUND.
You may print each character of the string in uppercase or lowercase (for example, the strings
FOUND, fouND, FouND, and found will all be treated as identical).
Constraints
● 100≤X≤999
Sample 1:
Input
200
Output
FOUND
Explanation:
Since the response code is not 404, website returns FOUND.
Sample 2:
Input
404
Output
NOT FOUND
Explanation:
Since the response code is 404, website returns NOT FOUND.
Sample 3:
Input
301
Output
FOUND
Explanation:
Since the response code is not 404, website returns FOUND.
Program :
X = int(input())
print("NOT FOUND" if X == 404 else "FOUND")
b. Python Try/Except — basic problem to handle division by zero and other
exceptions:
[Link]
Problem Statement:
Write a Python program that performs integer division of two numbers entered by the user.
The program must handle exceptions properly:
● If the user enters non-integer values, display an appropriate error message.
● If the user attempts to divide by zero, display a specific error message.
Use try and except blocks to handle these exceptions.
Input Format:
● A single line containing two space-separated values.
Output Format:
● Print the result of integer division if inputs are valid.
● If division by zero occurs, print:
Error: division by zero
● If invalid input is given, print:
● Error: invalid input
Test Cases:
Test Case 1:
Input:
10 2
Output:
5
Test Case 2:
Input:
7 3
Output:
2
Program :
try:
a, b = map(int, input().split())
print(a // b)
except ZeroDivisionError:
print("Error: division by zero")
except ValueError:
print("Error: invalid input")
c. Handling Multiple Exceptions — practise catching multiple exception types in one
block:
Problem Statement:
Write a Python program that reads two values from the user and performs integer division.
The program should handle errors using exception handling.
● If the inputs are not valid integers or
● If division by zero occurs,
the program should display a common error message.
Input Format:
● A single line containing two space-separated values.
Output Format:
● Print the result of integer division if inputs are valid.
● Otherwise, print:
Error occurred
Test Cases:
Test Case 1:
Input:
10 2
Output:
5
Test Case 2:
Input:
9 3
Output:
3
Program :
try:
a, b = map(int, input().split())
result = a // b
print(result)
except (ZeroDivisionError, ValueError):
print("Error occurred")
d. Show file handling using try/finally and with statements.
[Link]
Problem Statement
Valid Minimum
There are 3 hidden numbers A,B,C.
You somehow found out the values of min(A,B),min(B,C), and min(C,A).
Determine whether there exists any tuple (A,B,C) that satisfies the given values of
min(A,B),min(B,C),min(C,A).
Input Format
● The first line of input will contain a single integer T, denoting the number of test cases.
● The first and only line of each test case contains 3 space-separated integers denoting
the values of min(A,B),min(B,C), and min(C,A).
Output Format
For each test case, output YES if there exists any valid tuple (A,B,C), and NO otherwise.
You can print each letter of the output in any case. For example YES, yes, yEs will all be
considered equivalent.
Constraints
● 1≤T≤1000
● 1≤min(A,B),min(B,C),min(C,A)≤10
Sample 1:
Input
3
5 5 5
2 3 4
2 2 4
Output
YES
NO
YES
Explanation:
Test case 1: One valid tuple (A,B,C) is (5,5,5).
Test case 2: It can be shown that there is no valid tuple (A,B,C).
Test case 3: One valid tuple (A,B,C) is (4,2,5).
Program :
T = int(input())
for _ in range(T):
vals = list(map(int, input().split()))
[Link]()
print("YES" if vals[0] == vals[1] else "NO")
2. Integrated Problem Solving
a. Implement the Hangman game using string logic and loops
[Link]
Problem Statement
Palindromic substrings
Read problems statements in Mandarin Chinese, Russian and Vietnamese as well.
Chef likes strings a lot but he likes palindromic strings more. Today, Chef has two strings A
and B, each consisting of lower case alphabets.
Chef is eager to know whether it is possible to choose some non empty strings s1 and s2
where s1 is a substring of A, s2 is a substring of B such that s1 + s2 is a palindromic string.
Here '+' denotes the concatenation between the strings.
Note:
A string is a palindromic string if it can be read same both forward as well as backward. To
know more about palindromes click here.
Input
● First line of input contains a single integer T denoting the number of test cases.
● For each test case:
● First line contains the string A
● Second line contains the string B.
Output
For each test case, Print "Yes" (without quotes) if it possible to choose such strings s1 & s2.
Print "No" (without quotes) otherwise.
Constraints
● 1 ≤ T ≤ 10
● 1 ≤ |A|, |B| ≤ 1000
Subtasks
● Subtask 1: 1 ≤ |A|, |B| ≤ 10 : ( 40 pts )
● Subtask 2: 1 ≤ |A|, |B| ≤ 1000 : ( 60 pts )
Sample 1:
Input
3
abc
abc
a
b
abba
baab
Output
Yes
No
Yes
Explanation:
● Test 1: One possible way of choosing s1 & s2 is s1 = "ab", s2 = "a" such that s1 + s2 i.e
"aba" is a palindrome.
● Test 2: There is no possible way to choose s1 & s2 such that s1 + s2 is a palindrome.
● Test 3: You can figure it out yourself.
Program :
T = int(input())
for _ in range(T):
A = input().strip()
B = input().strip()
print("Yes" if set(A) & set(B) else "No")