Python Programming
Python Programming
Week 1
PPA 1
Print the first 5 positive integers in ascending order with one number
in each line
for i in range (5):
print(i+1)
PPA 2
Print the following pattern.
*
**
***
****
*****
There are no spaces between consecutive stars. There are no spaces
at the end of each line.
for i in range (1,6):
for j in range(1,i+1):
print("*", end = '')
print()
PPA 3
Accept an integer as input and print its square as output.
n = int(input())
print(n**2)
PPA 4
Accept two integers as input and print their sum as output.
a = int(input())
b = int(input())
print(a+b)
PPA 5
Accept two words as input and print the two words after adding a
space between them.
print(input(), input())
PPA 6
Accept the registration number of a vehicle as input and print its
state-code as output.
s = input()
print(s[0:2])
PPA 7
Accept a five-digit number as input and print the sum of its digits as
output.
num = input()
d1 = int(num[0])
d2 = int(num[1])
d3 = int(num[2])
d4 = int(num[3])
d5 = int(num[4])
dsum = d1 + d2 + d3 + d4 + d5
print(dsum)
GrPA 1
Accept five words as input and print the sentence formed by these
words after adding a space between consecutive words and a full stop
at the end.
word1 = input()
word2 = input()
word3 = input()
word4 = input()
word5 = input()
space = ' '
stop = '.'
sentence = word1 + space + word2 + space + word3 + space + word4 + space +
word5 + stop
print(sentence)
GrPA 2
Accept the date in DD-MM-YYYY format as input and print the
year as output.
date = input()
year = date[-4: ]
print(year)
GrPA 3
Accept a sequence of five single digit numbers separated by commas
as input. Print the product of all five numbers.
num = input()
d1 = int(num[0])
d2 = int(num[2])
d3 = int(num[4])
d4 = int(num[6])
d5 = int(num[8])
dprod = d1 * d2 * d3 * d4 * d5
print(dprod)
GrPA 4
Assume that several IITs start offering online degrees across
multiple branches. The email-id of a student is defined as
follows:
branch_degree_year_roll@student.onlinedegree.institute.ac.in
For example, if the email-id
is CS_BT_21_7412@student.onlinedegree.iitm.ac.in, then this
student is from the computer science branch, pursuing a BTech
degree from IITM, starting from the year 2021, with 7412 as the
roll number. branch, degree and year are codes of length two,
while roll and institute are codes of length four. Accept a
student's email-id as input and print the following details, one
item on each line: (1) Branch (2) Degree (3) Year (4) Roll
number (5) Institute
email = input()
branch = email[:2]
degree = email[3: 5]
year = email[6:8]
roll = email[9:13]
institute = email[-10:-6]
print(branch)
print(degree)
print(year)
print(roll)
print(institute)
GrPA 5
Accept two positive integers x and y as input. Print the number of
digits in xy.
x = int(input())
y = int(input())
res = x ** y
res_str = str(res)
print(len(res_str))
GrPA 6
Accept two positive integers M and N as input. There are two cases
to consider: (1) If M < N, then print M as output. (2) If M >= N,
subtract N from M. Call the difference M1. If M1 >= N, then
subtract N from M1 and call the difference M2. Keep doing this
operation until you reach a value k, such that, Mk < N. You have to
print the value of Mk as output.
M = int(input())
N = int(input())
print(M % N)
Week 2
PPA 1
Accept a non-zero integer as input. Print positive if it is
greater than zero and negative if it is less than zero.
n = int(input() )
if n>0:
print('positive')
else:
print('negative')
PPA 2
Consider the piece-wise function given below.
𝑥+2 0 < 𝑥 < 10
f(x) = {𝑥 2 + 2 10 ≤ 𝑥
0 𝑜𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒
Accept the value of x as input and print the value of f(x) as output.
Note that both the input and output are real numbers. Your code
should reflect this aspect. That is, both x and f(x) should be float
values.
x = float(input())
if 0<x<10:
print(x+2)
elif(10<=x):
print(x**2+2)
else:
print(0)
PPA 3
T = int(input())
if T<0:
print('INVALID')
elif 0<=T<=5:
print('NIGHT')
elif 6<=T<=11:
print('MORNING')
elif 12<=T<=17:
print('AFTERNOON')
elif 18<=T<=23:
print('EVENING')
else:
print('INVALID')
PPA 4
Accept a point in 2D space as input and find the region in space that this point belongs to. A
point could belong to one of the four quadrants, or it could be on one of the two axes, or it
could be the origin. The input is given in 2 lines: the first line is the x-coordinate of the point
while the second line is its y-coordinate. The possible outputs
are first, second, third, fourth, x-axis, y-axis, and origin. Any other output will not be
accepted. Note that all outputs should be in lower case.
x = float(input())
y = float(input())
if x>0:
if y>0:
print("first")
elif y<0:
print("fourth")
elif(y==0):
print("x-axis")
if x<0:
if y>0:
print("second")
elif(y<0):
print("third")
elif(y==0):
print("x-axis")
if x==0:
if y==0:
print("origin")
else:
print("y-axis")
PPA 5
Write a program to realize the equation of a line given 2
points (x1,y1) and (x2,y2) in 2D space. The input is in 5 lines where,
the first, second, third, and fourth lines represent x1, y1, x2,
and y2 respectively. The fifth line corresponds to x3.
Determine y3 using the equation of a straight line as given below:
𝑥−𝑥1 𝑦−𝑦1
=
𝑥2 −𝑥1 𝑦2 −𝑦1
The output should be "Vertical Line" if the line is vertical. In other
cases, the output should be 2 lined, where the first line is the value
of y3 and the second line indicates whether the slope of the line is
positive, negative or zero. Print "Positive Slope", "Negative Slope" or
"Horizontal Line" accordingly.
Note that all inputs are to be processed as real numbers.
x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = float(input())
x3 = float(input())
if x1==x2:
print("Vertical Line")
else:
slope = (y2-y1)/(x2-x1)
y3 = y1 + slope*(x3-x1)
print(y3)
if slope>0:
print("Positive Slope")
elif slope<0:
print("Negative Slope")
else:
print("Horizontal Line")
PPA 6
Accept a string as input. If the input string is of odd length, then
continue with it. If the input string is of even length, make the
string of odd length as below:
• If the last character is a period (.), then remove it
• If the last character is not a period, then add a period (.) to the
s = input()
n = len(s)
if n%2 == 0:
if s[n-1]=='.':
s=s[:-1]
else:
s=s+'.'
n = int((len(s)-1)/2)
print(s[n-1: n+2])
PPA 7
A sequence of five words is called magical if the ith word is a substring of the (i+1)th word for every i
in range 1≤ i < 5. Accept a sequence of five words as input, one word on each line. Print magical if
the sequence is magical and non-magical otherwise.
Note that str_1 is a substring of str_2 if and only if str_1 is present as a sequence of consecutive
characters in str_2.
a = input()
b = input()
c = input()
d = input()
e = input()
if(a in b and b in c and c in d and d in e):
print("magical")
else:
print("non-magical")
PPA 8
Accept two positions as input: start and end. Print YES if a bishop
at start can move to end in exactly one move.
Print NO otherwise. Note that a bishop can only move along
diagonals.
start = input()
end = input()
s = 'ABCDEFGH'
if(abs(s.index(start[0])-s.index(end[0])))==abs(int(start[1]) - int(end[1])):
print('YES')
else:
print('NO')
PPA 9
You have n gold coins with you. You wish to divide this among three
of your friends under the following conditions:
(3) You should not have any coins with you at the end of this sharing
process.
The input has four lines. The first line contains the number of coins
with you. The next three lines will have the share given to your three
friends. All inputs shall be non-negative integers. If the division
satisfies these conditions, then print the string FAIR. If not, print UNFAIR.
n=int(input())
n1=int(input())
n2=int(input())
n3=int(input())
if n1>0 and n2>0 and n3>0 and n1+n2+n3==n and n1!=n2 and n2!=n3 and n3!=n1 :
print('FAIR')
else:
print('UNFAIR')
PPA 10
Accept a real number x as input and print the greatest integer less
than or equal to x on the first line, followed by the smallest integer
greater than or equal to x on the second line.
x = float(input())
n = int(x)
if x==n:
print(n)
print(n)
elif(x>0):
print(n)
print(n+1)
else:
print(n-1)
print(n)
GrPA 1
Accept three positive integers as input and check if they form the
sides of a right triangle. Print YES if they form one, and NO is they do
not. The input will have three lines, with one integer on each line.
The output should be a single line containing one of these two
strings: YES or NO.
x = int(input())
y = int(input())
z = int(input())
GrPA 2
EvenOdd is a tech startup. Each employee at the startup is given an employee id which is a unique
positive integer. On one warm Sunday evening, five employees of the company come together for a
meeting and sit at a circular table:
The employees follow a strange convention. They will continue the meeting only if the following
condition is satisfied.
The sum of the employee-ids of every pair of adjacent employees at the table must be an even
number.
They are so lazy that they won’t move around to satisfy the above condition, If the current seating
plan doesn’t satisfy the condition, the meeting will be cancelled. You are given the employee-id of all
five employees. Your task is to decide if the meeting happened or not.
The input will be five lined, each containing an integer. The ith line will have the employee-id of Ei.
The output will be a single line containing one of these two strings: YES or NO.
e1 = int(input())
e2 = int(input())
e3 = int(input())
e4 = int(input())
e5 = int(input())
# Check if the sum is odd for each pair of adjacent employees
if (e1 + e2) % 2 != 0:
print('NO')
elif (e2 + e3) % 2 != 0:
print('NO')
elif (e3 + e4) % 2 != 0:
print('NO')
elif (e4 + e5) % 2 != 0:
print('NO')
elif (e5 + e1) % 2 != 0:
print('NO')
# If the sum is even for every pair of adjacent employees,
# then the else block gets executed
else:
print('YES')
GrPA 3
Accept a string as input and print the vowels present in the string in
alphabetical order. If the string doesn’t contain any vowels, then
print the string none as output. Each vowel that appears in the input
string – irrespective of its case should appear just once in lower case
in the output.
input_string = input().lower()
vowels = ""
if "a" in input_string:
vowels += "a"
if "e" in input_string:
vowels += "e"
if "i" in input_string:
vowels += "i"
if "o" in input_string:
vowels += "o"
if "u" in input_string:
vowels += "u"
# check if vowels is non-empty
if vowels != "":
print(vowels)
else:
print('none')
GrPA 4
You are given the date of birth of two persons, not necessarily from
the same family. Your task is to find the younger of the two. If both
of them share the same date of birth, then the younger of the two is
assumed to be that person whose name comes first in alphabetical
order.
The input will have four lines. The first two lines correspond to the
first person, while the last two lines correspond to the second
person. For each person, the first line corresponds to the name and
the second line corresponds to the date of birth in “DD-MM-YYYY”
format. Your output should be the name of the younger of the two.
n1 = input()
d1 = input()
n2 = input()
d2 = input()
if d1==d2 :
if n1<n2 :
print(n1)
else :
print(n2)
elif d1[-4:] != d2[-4:] :
if int(d1[-4:]) < int(d2[-4:]):
print(n2)
else :
print(n1)
elif d1[3:5] != d2[3:5]:
if int(d1[3:5]) < int(d2[3:5]):
print(n2)
else :
print(n1)
else :
if int(d1[0:2]) < int(d2[0:2]):
print(n2)
else :
print(n1)
GrPA 5
Accept a string as input. Your task is to determine if the input string is a valid password or not. For a
string to be a valid password, it must satisfy all the conditions given below:
It could have any character that is not mentioned in the list of characters to be avoided (points 3 and
4). Output True if the string forms a valid password and False otherwise.
p = input()
if 8<= len(p) <= 32 and p[0].isalpha() and '/' not in p and '\\' not in p and
'=' not in p and '\'' not in p and '\"' not in p and ' ' not in p :
print('True')
else:
print('False')
Week 3
PPA 1
Accept a positive integer n as input and print the first n positive
integers, one number on each line.
n = int(input())
for i in range(1,n+1):
print(i)
PPA 2
Accept a positive integer n as input and print all the factors of n, one
number on each line.
n = int(input())
for i in range(1,n+1):
if n%i==0:
print(i)
PPA 3
Accept two positive integers a and b as input. Print the sum of all
integers in the range [1000, 2000], endpoints inclusive, that are
divisible by both a and b. If you find no number satisfying this
condition in the given range, then print 0.
a = int(input())
b = int(input())
n = 0
for i in range(1000,2001):
if i%a==0 and i%b==0:
n+=i
print(n)
PPA 4
Accept a positive integer n as input, where n is greater than 1.
PPA 5
Accept a sequence of positive integers as input and print the the
maximum number in the sequence. The input will have n + 1 lines,
where n denotes the number of terms in the sequence. The ith line in
the input will contain the ith term in the sequence for 1 <= i <= n.
The last line of the input will always be the number 0. Each test case
will have at least one term in the sequence.
n = int(input())
max = 0
while(n!=0):
if max < n:
max = n
n = int(input())
print(max)
PPA 6
Accept a sequence of words as input and print the the shortest word
in the sequence. The input will have n + 1 lines, where n denotes
the number of terms in the sequence. The ith line in the input will
contain the ith word in the sequence for 1 <= i <= n. The last line
of the input will always be the
string abcdefghijklmnopqrstuvwxyz. This string is not a
part of the sequence. You can assume that each test case
corresponds to a non-empty sequence of words. If there are multiple
words that have the same minimum length, print the first such
occurrence.
s = input()
small = s
while (s!= 'abcdefghijklmnopqrstuvwxyz'):
if(len(s))<len(small):
small = s
s = input()
print(small)
PPA 7
Accept a positive integer as input and print the sum of the digits in
the number.
n = input()
sum = 0
for i in n:
sum += int(i)
print (sum)
PPA 8
Accept a positive integer n as input and print the first n integers on a
line separated by a comma.
n = int(input())
for i in range (1,n):
print(i, end=',')
print(n)
PPA 9
n = int(input())
for i in range(1,n+1):
for j in range(1,i+1):
print(0,end = '')
print()
PPA 10
Accept a positive integer n as input and print the sum of all prime
numbers in the range [1, n], endpoints inclusive. If there are no
prime numbers in the given range, then print 0.
n = int(input())
sum = 0
prime = True
for i in range(2,n+1):
for j in range (2,i):
if i%j == 0:
prime = False
if prime:
sum+=i
prime = True
print(sum)
PPA 11
Accept a positive integer n as input and find all solutions to the
equation:
x2+y2=z2
subject to the following constraints:
(1) x, y and z are positive integers
(2) x<y<z<n
Print each solution triplet on one line — x,y,z — with a comma
between consecutive integers. The triplets should be printed in
ascending order. If you do not find any solutions satisfying the given
constraints, print the string NO SOLUTION as output.
Order relation among triplets
Given two triplets T1 = (x1, y1, z1) and T2 = (x2, y2, z2), use the following
process to compare them:
(1) If x1 < x2, then T1 < T2
(2) If x1 = x2 and y1< y2, then T1 < T2
(3) If x1 = x2 and y1= y2 and z1< z2, then T1 < T2
n=int(input())
c=True
for x in range(1,n):
for y in range(1,n):
for z in range(1,n):
if (x*x)+(y*y)==z*z and x<y<z<n:
print(x,y,z, sep=',')
c=False
if c:
print('NO SOLUTION')
PPA 12
Accept two strings as input and form a new string by removing all
characters from the second string which are present in the first string.
Print this new string as output. You can assume that all input strings
will be in lower case.
a = input()
b = input()
for c in a:
if c in b:
b = b.replace(c,'')
print(b)
GrPA 1
Accept a positive integer n as input and print the sum of the
first n terms of the series given below:
1 + (1 + 2) + (1 + 2 + 3) + (1 + 2 + 3 + 4) + ...
Just to be clear, the first term in the series is 1, the second term is (1 +
2) and so on.
n = int(input())
total = 0
for i in range(1, n + 1):
for j in range(1, i + 1):
total = total + j
print(total)
GrPA 2
Accept a positive integer n, with n > 1, as input from the user and
print all the prime factors of n in ascending order.
n = int(input())
for f in range(2, n + 1):
# first check if f is a factor of n
if n % f == 0:
# now check if f is a prime
is_prime = True
for i in range(2, f):
if f % i == 0:
is_prime = False
break
if is_prime:
print(f)
GrPA 3
A bot starts at the origin — (0,0) — and can make the following moves:
• UP
• DOWN
• LEFT
• RIGHT
Each move has a magnitude of 1 unit. Accept the sequence of moves made by the bot as input. The
first entry in the sequence is always START while the last entry in the sequence is always STOP. A
sample sequence is given below:
START
UP
RIGHT
LEFT
LEFT
DOWN
UP
STOP
Print the Manhattan distance of the bot from the origin. If the bot is at the position (x, y), then its
Manhattan distance from the origin is given by the equation:
D = |x|+|y|
GrPA 4
Accept a string as input, convert it to lower case, sort the string in
alphabetical order, and print the sorted string to the console. You can
assume that the string will only contain letters.
s=input().lower()
a='abcdefghijklmnopqrstuvwxyz'
t=''
for x in a:
for y in s:
if x==y:
t+=y
print(t)
GrPA 5
Accept a phone number as input. A valid phone number should satisfy
the following constraints.
(1) The number should start with one of these digits: 6, 7, 8, 9
(2) The number should be exactly 10 digits long.
(3) No digit should appear more than 7 times in the number.
(4) No digit should appear more than 5 times in a row in the
number.
If the fourth condition is not very clear, then consider this example:
the number 9888888765 is invalid because the digit 8 appears more
than 5 times in a row. Print the string valid if the phone number is
valid. If not, print the string invalid.
n=input()
a=False
if len(n)==10 and int(n[0])>5 and n.isdigit():
for i in range(10):
if n.count(n[i])<8:
a=True
if n[i]*6 in n:
a=False
break
else:
break
if a:
print('valid')
else:
print('invalid')
GrPA 6
Accept a positive integer n as input and print a "number arrow" of
size n. For example, n = 5 should produce the following output:
1
1,2
1,2,3
1,2,3,4
1,2,3,4,5
1,2,3,4
1,2,3
1,2
1
You can assume that n is greater than or equal to 2 for all test
cases. Hint: range(5, 0, -1) is the sequence 5, 4, 3, 2, 1
n=int(input())
for i in range(1,n+2):
for j in range(1,i):
if j<i-1:
print(j,end=',')
else:
print(j)
for i in range(n,0,-1):
for j in range(1,i):
if j<i-1:
print(j,end=',')
else:
print(j)
Week 4
PPA 1
Accept a positive integer n as input and print the list of first n positive integers as output.
n = int(input())
l=[]
for i in range(1,n+1):
l.append(i)
print(l)
PPA 2
Accept a sequence of words as input, append all these words to a list in the order in which
they are entered, and print this list as output. The first line in the input is a positive
integer n that denotes the number of words in the sequence. The next n lines will have one
word on each line.
n = int(input())
l=[]
for i in range(n):
x = input()
l.append(x)
print(l)
PPA 3
Accept a sequence of comma-separated integers as input and print the maximum value in the
sequence as output.
Hint:
When in doubt, always print the variables and examine the output.
1num = '1,2,3,4,5'
2L = num.split(',')
num = input().split(',')
max = -1
for i in range(len(num)):
if(int(num[i])>max):
max = int(num[i])
print(max)
PPA 4
This question introduces you to the idea of prefix codes. Prefix code is a block of visible code that is
already provided to you. You have to type your code below the prefix code. Note that the contents of
the prefix cannot be modified.
A list L of words is already given to you as a part of the prefix code. Print the longest word in the list.
If there are multiple words with the same maximum length, print the one which appears at the
rightmost end of the list.
You do not have to accept input from the console as it has already been provided to you
L = input().split(',')
max=0
m=''
for i in range(len(L)):
if len(L[i])>=max:
max=len(L[i])
m=''
m+=L[i]
print(m)
PPA 5
Accept a space-separated sequence of positive real numbers as input. Convert each
element of the sequence into the greatest integer less than or equal to it. Print this sequence
of integers as output, with a comma between consecutive integers.
x=input()
r=x.split(' ')
i = 0
s=''
while i<( len(r)-1) :
n = int(float(r[i]))
s += str(n)+','
i += 1
n= int(float(r[i]))
s += str(n)
print(s)
PPA 6
Accept a sequence of comma-separated words as input. Reverse the sequence and print it as output.
Hint:
1print([1] + [2])
2print([2] + [1])
l=input().split(',')
for i in range(len(l)-1,0,-1):
print(l[i],end=',')
print(l[0])
PPA 7
This question introduces you to the idea of suffix codes. Suffix code is a block of visible code that
will be executed after whatever code you type. You have to type your code above the suffix code.
Note that the contents of the suffix code cannot be modified.
Accept a square matrix as input and store it in a variable named matrix. The first line of input will
be, n, the number of rows in the matrix. Each of the next n lines will have a sequence of n space-
separated integers.
You do not have to print the output to the console as the suffix code already does that for you.
matrix=[]
n=int(input())
for i in range(n):
f=input().split(' ')
for j in range(n):
f[j]=int(f[j])
matrix.append(f)
print(matrix)
PPA 8
An identity matrix is a square matrix which has ones on the main diagonal and zeros
everywhere else. For example, the identity matrix of size 3×3 is:
𝟏 𝟎 𝟎
[𝟎 𝟏 𝟎]
𝟎 𝟎 𝟏
Accept a positive integer n as input and print the identity matrix of size n×n. Your output
should have n lines, where each line is a sequence of n comma-separated integers that
corresponds to one row of the matrix.
n=int(input())
for i in range(0,n):
for j in range(0,n):
if(i==j):
if(j==(n-1)):
print('1')
else:
print('1',end=',')
else:
if(j==(n-1)):
print('0')
else:
print('0',end=',')
PPA 9
Accept a square matrix A and an integer s as input and print the matrix s⋅A as output. Multiplying a
matrix by an integer ss is equivalent to multiplying each element of the matrix by s. For example,
1 2 2 4
2∙[ ]=[ ]
3 4 6 8
The first line of input is a positive integer, n, that denotes the dimension of the matrix A. Each of the
next n lines contains a sequence of space-separated integers. The last line of the input contains the
integer s.
Print the matrix s⋅A as output. Each row of the matrix must be printed as a sequence of space
separated integers, one row on each line.
m=[]
n=int(input())
for i in range(n):
f=input().split(' ')
for j in range(n):
f[j]=int(f[j])
m.append(f)
s=int(input())
for i in range(n):
for j in range(n):
m[i][j]=m[i][j]*s
if j<(n-1):
print(m[i][j],end=' ')
else:
print(m[i][j])
PPA 10
Accept two square matrices A and B of dimensions n×n as input and compute their sum A + B.
The first line will contain the integer n. This is followed by 2n lines. Each of the first n lines is a
sequence of comma-separated integers that denotes one row of the matrix A. Each of the last n lines is
a sequence of comma-separated integers that denotes one row of the matrix B.
Your output should again be a sequence of n lines, where each line is a sequence of comma-separated
integer that denotes a row of the matrix A + B.
n=int(input())
a=[]
b=[]
for i in range(2):
for j in range(n):
f=[]
f=input().split(',')
for k in range(n):
f[k]=int(f[k])
if i==0:
a.append(f)
else:
b.append(f)
for i in range(n):
for j in range(n):
a[i][j]+=b[i][j]
if j<n-1:
print(a[i][j],end=',')
else:
print(a[i][j])
PPA 11
This question introduces you to two ideas that will keep repeating throughout this course:
• Entering your code within a function. We will cover functions next week. The only thing you
need to do for this problem is to indent all your code to the right by one unit (four spaces),
and paste this between the prefix and suffix code.
• The idea of invisible codes. Invisible code is a block of code that will be hidden from your
sight. The invisible code will modify the code that you write. But the details of the
modification will not be revealed to you.
L is a list of real numbers that is already given to you. You have to sort this list in descending
order and store the sorted list in a variable called sorted_L.
You do not have to accept input from the console as it has already been provided to you. You do
not have to print the output to the console. Input-Output is the responsibility of the invisible
code for this problem.
def solution(L):
### Enter your solution below this line
### Indent your entire code by one unit (4 spaces) to the right
for i in range (len(L)):
for j in range(i + 1, len(L)):
if(L[i] < L[j]):
t = L[i]
L[i] = L[j]
L[j] = t
sorted_L=L
### Enter your solution above this line
return sorted_L
GrPA 1
In the first line of input, accept a sequence of space-separated words. In the second line of
input, accept a single word. If this word is not present in the sequence, print NO. If this word
is present in the sequence, then print YES and in the next line of the output, print the number
of times the word appears in the sequence.
s=input().split(' ')
a=input()
if a in s:
print('YES')
print(s.count(a))
else:
print('NO')
GrPA 2
You are given a list marks that has the marks scored by a class of students in a Mathematics test.
Find the median marks and store it in a float variable named median. You can assume that marks is
a list of float values.
You do not have to accept input from the console as it has already been provided to you. You do not
have to print the output to the console. Input-Output is the responsibility of the autograder for this
problem. Refer PPA-11 if you are not sure how this works.
def solution(marks):
### Enter your solution below this line
### Indent your entire code by one unit (4 spaces) to the right
marks_sort = []
for x in range(len(marks)):
marks_sort.append(min(marks))
marks.remove(min(marks))
if len(marks_sort)%2 ==0:
median = (((marks_sort[(int(len(marks_sort)//2))-1] +
marks_sort[(int(len(marks_sort)//2)+1)-1])/2))
elif len(marks_sort)%2 != 0:
median = (marks_sort[(((int(len(marks_sort)))+1)//2)-1])
### Enter your solution above this line
return median
GrPA 3
Accept two square matrices A and B of dimensions n×n as input and compute their product AB.
The first line of the input will contain the integer n. This is followed by 2n lines. Out of these, each of
the first n lines is a sequence of comma-separated integers that denotes one row of the matrix A. Each
of the last n lines is a sequence of comma-separated integers that denotes one row of the matrix B.
Your output should again be a sequence of n lines, where each line is a sequence of comma-separated
integers that denotes a row of the matrix AB.
n = int(input())
# Accept matrix A
A = [ ]
for i in range(n):
row = [ ]
for x in input().split(','):
row.append(int(x))
A.append(row)
# Accept matrix B
B = [ ]
for i in range(n):
row = [ ]
for x in input().split(','):
row.append(int(x))
B.append(row)
# Matrix product
for i in range(n):
for j in range(n):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]
if j != n - 1:
print(C[i][j], end = ',')
else:
print(C[i][j])
GrPA 4
You are given the names and dates of birth of a group of people. Find all pairs of members who share
a common date of birth. Note that this date need not be common across all pairs. It is sufficient if both
members in a pair have the same date of birth.
The first line of input is a sequence of comma-separated names. The second line of input is a sequence
of comma-separated positive integers. Each integer in the sequence will be in the range [1, 365],
endpoints inclusive, and stands for some day in the year.
Find all pairs of names that share a common date of birth and store them in a list called common.
Each element of this list is itself a list, and should be of the form [name1, name2], such
that name1 comes before name2 in alphabetical order.
names = input().split(',')
bdays = input().split(',')
n = len(names)
for i in range(n):
bdays[i] = int(bdays[i])
common = [ ]
for i in range(n):
for j in range(n):
if ((i != j) and
(bdays[i] == bdays[j]) and
names[i] < names[j]):
pair = [names[i], names[j]]
common.append(pair)
GrPA 5
You are given a sequence of n points, (xi,yi), 1≤i≤n, in the 2-D plane as input. Also, you are given a
point P with coordinates (x,y). Print all points in the sequence that are nearest to P. If multiple points
have the same least distance from P, print the points in the order of their appearance in the sequence.
The first line of the input is an integer n, representing the number of points in the sequence. Each of
the next n lines contains the co-ordinates of a point separated by comma. The last line contains
the x and y co-ordinates of the point P. Assume that all the x and y co-ordinates are integers.
The distance between two points (x1, y1) and (x2, y2) is √(𝑥1 − 𝑥2 )2 + (𝑦1 − 𝑦2 )2 . You can assume
that the maximum distance from P to any point will not exceed 1000.
n = int(input())
L = [ ]
# Append all points in the sequence to the list L
for i in range(n):
L.append(input())
# Point P
point = input().split(',')
x = int(point[0])
y = int(point[1])
Week 5
PPA 1
Type: single argument, single return value
The factorial of a positive integer n is the product of the first n positive integers.
Write a function named factorial that accepts an integer n as argument. It should return
the factorial of n if n is a positive integer. It should return -1 if n is a negative integer, and it
should return 1 if n is zero.
1def factorial(n):
2 '''
3 Argument:
4 n: integer
5 Return:
6 result: integer
7 '''
You do not have to accept input from the user or print output to the console. You just have to
write the function definition.
def factorial(n):
if n<0:
return -1
elif n==0:
return 1
else:
f=1
for i in range(1,n+1):
f*=i
return f
PPA 2
In the Gregorian calendar, a leap year has a total of 366 days instead of the usual 365 as a result of
adding an extra day (February 29) to the year. This calendar was introduced in 1582 to replace the
flawed Julian Calendar. The criteria given below are used to determine if a year is a leap year or not.
• If a year is divisible by 100 then it will be a leap year if it is also divisible by 400.
• If a year is not divisible by 100, then it will be a leap year if it is divisible by 4.
Write a function named check_leap_year that accepts a year between 1600 and 9999 as
argument. It should return True if the year is a leap year and False otherwise.
1def check_leap_year(year):
2 '''
3 Argument:
4 year: integer
5 Return:
6 is_leap_year: bool
7 '''
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
def check_leap_year(year):
if year%100==0:
if year%400==0:
return True
else:
return False
else:
if year%4==0:
return True
else:
return False
PPA 3
Type: multiple arguments, single return value
Write a function named maxval that accepts three integers a, b and c as arguments. It should return
the maximum among the three numbers.
PPA 4
Write a function named dim_equal that accepts two matrices A and B as arguments. It should
return True if the the dimensions of both matrices are the same, and False otherwise.
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
PPA 5
Type: single argument, multiple return values
Write a function named first_three that accepts a list L of distinct integers as argument. It
should return the first maximum, second maximum and third maximum in the list, in this order. You
can assume that the input list will have a size of at least three. What concept in CT does this remind
you of?
1def first_three(L):
2 '''
3 Argument:
4 L: list
5 Return:
6 fmax, smax, tmax: three integers
7 '''
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
def first_three(L):
fmax=-10000
smax=-10000
tmax=-10000
for i in range(len(L)):
if L[i]>fmax:
fmax,smax,tmax=L[i],fmax,smax
elif L[i]>smax:
smax,tmax=L[i],smax
elif L[i]>tmax:
tmax=L[i]
return fmax,smax,tmax
PPA 6
Function Calls
A class of English words is called mysterious if it satisfies certain conditions. These conditions are
hidden from you. Instead, you are given a function named mysterious that accepts a word as
argument and returns True if the word is mysterious and False otherwise.
Write a function named type_of_sequence that accepts a list of words as an argument. Its return
value is a string that depends on the number of mysterious words in the sequence. The exact
conditions are given in the following table. If k denotes the number of mysterious words in the
sequence, then:
k Return value
1def type_of_sequence(L):
2 '''
3 Argument:
4 L: list of strings
5 Return:
6 seq_type: string
7 '''
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
def type_of_sequence(L):
k=0
for i in range(len(L)):
if mysterious(L[i]):
k+=1
if k<2:
return 'mildly mysterious'
elif k<5:
return 'moderately mysterious'
else:
return 'most mysterious'
PPA 7
In a throwback to CT days, write the definition of the following five functions, all of which accept a
list L as argument.
(1) is_empty: return True if the list is empty, and False otherwise.
(2) first: return the first element if the list is non-empty, return None otherwise.
(3) last: return the last element if the list is non-empty, return None otherwise.
(4) init: return the first n - 1n−1 elements if the list is non-empty and has size nn,
return None otherwise. Note that if L has just one element, init(L) should return the empty list.
(5) rest: return the last n - 1n−1 elements if the list is non-empty and has size nn,
return None otherwise. Note that if L has just one element, rest(L) should return the empty list.
You do not have to accept input from the user or print output to the console. You just have to write
the definition of all the five functions. Each test case corresponds to one function call.
def is_empty(l):
if len(l)==0:
return True
else:
return False
def first(l):
if not is_empty(l):
return l[0]
else:
return 'None'
def last(l):
if not is_empty(l):
return l[-1]
else:
return 'None'
def init(l):
if not is_empty(l):
return l[:-1]
else:
return 'None'
def rest(l):
if not is_empty(l):
return l[1:]
else:
return 'None'
PPA 8
Write a recursive function named fibo that accepts a positive integer n as argument and returns
the nth Fibonacci number. For this problem, F1=F2=1 are the first two Fibonacci numbers.
1 def fibo(n):
2 '''
3 Argument:
4 n: int
5 Return:
6 f_n: int
7 '''
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
def fibo(n):
if n==1 or n==2:
return 1
else:
f=0
f=fibo(n-1)+fibo(n-2)
return f
PPA 9
Implement the following functions.
(1) Write a function named get_column that accepts a matrix named mat and a non-negative
integer named col as arguments. It should return the column that is at index col in the
matrix mat as a list. Zero-based indexing is used here.
(2) Write a function named get_row that accepts a matrix named mat and a non-negative integer
named row as arguments. It should return the row that is at index row in the matrix mat as a list.
Zero-based indexing is used here.
You do not have to accept input from the user or print output to the console. You just have to write
the definition of both the functions. Each test case will correspond to one function call.
PPA 10
Write a function named insert that accepts a sorted list L of integers and an integer x as input. The
function should return a sorted list with the element x inserted at the right place in the input list. The
original list should not be disturbed in the process. You can assume that the input list will be sorted in
ascending order.
(1) The only built-in methods you are allowed to use are append and remove. You should not use
any other method provided for lists.
(2) You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
GrPA 1
The range of a list of numbers is the difference between the maximum and minimum values in the list.
Write a function named get_range that accepts a non-empty list of real numbers as argument. It
should return the range of the list.
1 def get_range(L):
2 '''
3 Argument:
4 L: list
5 Return:
6 range: float
7 '''
Note
(1) Avoid using built-in function such as max and min.
(2) You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
Write a function named is_perfect that accepts a positive integer n as argument and
returns True if it is a perfect number, and False otherwise.
1def is_perfect(n):
2 '''
3 Argument:
4 n: int
5 Return:
6 result: bool
7 '''
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
def is_perfect(num):
# Factor sum
fsum = 0
for f in range(1, num):
if num % f == 0:
fsum += f
# fsum == num is a Boolean expression
# It will evaluate to True if num is a perfect number
# And False otherwise
return fsum == num
print(is_perfect(int(input())))
GrPA 3
The distance between two different letters in the English alphabet is defined as one more than the
number of letters between them. Alternatively, it can be defined as the number of steps needed to
move from the alphabetically smaller letter to the larger letter. This is always a non-negative integer.
The distance between any letter and itself is always zero. For example:
a a dletter(a,a)=0
a c dletter(a,c)=2
Letter-1 Letter-2 Distance
a z dletter(a,z)=25
z a dletter(z,a)=25
e a dletter(e,a)=4
Write a function named distance that accepts two words as arguments and returns the distance
between them.
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
Write a function named is_magic that accepts a square matrix as argument and returns YES if it is
a magic-square and NO if it isn't one.
1def is_magic(mat):
2 '''
3 Argument:
4 mat: list of lists
5 Return:
6 string: 'YES' or 'NO'
7 '''
Notes
(1) The cells of a magic square need not be distinct. Some or even all the cells could be identical.
(2) You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
A sample-image for a 3X3 matrix that details the various sums needed. Note that the input need not be
restricted to 3X3 matrices:
def is_magic(mat):
# first get the dimension of the matrix
m = len(mat)
# the sum of the two diagonals
d1sum, d2sum = 0, 0
# (i, i) goes from top-left -> bottom-right
# (i, m - i - 1) goes from top-right -> bottom-left
# note that a single loop is enough; no nesting required
for i in range(m):
d1sum += mat[i][i]
d2sum += mat[i][m - i - 1]
# if the two diagonal sums are unequal, we can return NO
# unnecessary computation can be avoided
if not(d1sum == d2sum):
return 'NO'
# get row-sum and column-sum
for i in range(m):
rsum, csum = 0, 0
for j in range(m):
rsum += mat[i][j]
csum += mat[j][i]
if not(rsum == csum == d1sum):
return 'NO'
# if the code reaches this level
# then all requirements of a magic-square are satisfied
# so we can safely return YES
return 'YES'
GrPA 5
The transpose of a matrix is obtained by swapping its rows and columns:
a d
a b c
[ ] → [b e ]
d e f
c f
Write a function named transpose that accepts a matrix mat as input and returns its transpose.
1 def transpose(mat):
2 '''
3 Argument:
4 mat: list of lists
5 Return:
6 mat_trans: list of lists
7 '''
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
Week 6
PPA 1
Accept a sequence of words as input. Create a dictionary named freq whose keys are the distinct
words in the sequence. The value corresponding to a key (word) should be the frequency of
occurrence of the key (word) in the sequence.
(1) You can assume that all words will be in lower case.
(2) You do not have to print the output to the console. This will be the responsibility of the
autograder.
freq = dict()
L = input().split(',')
for word in L:
freq[word] = 0
for word in L:
freq[word] = freq[word] + 1
PPA 2
Accept a positive integer as input and print the digits present in it from left to right. Each
digit should be printed as a lower case word on a separate line. How would you use
dictionaries to solve this problem?
num = input()
D = {'0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four',
'5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'}
PPA 3
Write the following functions:
(1) is_key: accept a dictionary D and a variable key as arguments. Return True if the
variable key is a key of the dictionary D, and False otherwise.
(2) value: accept a dictionary D and a variable key as arguments. If the variable key is not a key of
the dictionary D, return None, otherwise, return the value corresponding to this key.
You do not have to accept input from the user or print the output to the console. You just have to
write the definition of both the functions.
(1) You do not have to accept input from the user or print the output to the console. You just have to
write the definition of the function.
(2) The keys inside the list could be in any order.
PPA 5
Write the following functions:
(1) dict_to_list: accept a dictionary D as argument. Return the key-value pairs in D as a list L of
tuples. That is, every element of L should be of the form (key, value) such that D[key] = value.
Going the other way, every key-value pair in the dictionary should be present as a tuple in the list L.
(2) list_to_dict: accept a list of tuples L as argument. Each element of L is of the form (x,
y). Return a dict D such that each tuple (x, y) corresponds to a key-value pair in D. That is, D[x] =
y.
1 def dict_to_list(D):
2 '''
3 Argument:
4 D: dict
5 Return:
6 L: list of tuples
7 '''
8 pass
9
10def list_to_dict(L):
11 '''
12 Argument:
13 L: list of tuples
14 Return:
15 D: dict
16 '''
17 pass
(1) For the function dict_to_list(D), the order in which the key-value pairs are appended to the
list doesn't matter.
(2) For the function list_to_dict(L), you can assume that if (x1, y1) and (x2, y2) are
two different elements in L, x1 != x2. Why is this assumption important?
(3) You do not have to accept input from the user or print the output to the console. You just have to
write the definition of both the functions.
def dict_to_list(D):
L = [ ]
for key in D:
L.append((key, D[key]))
return L
def list_to_dict(L):
D = dict()
return D
PPA 6
Scores Dataset Revisited
Recall the Scores dataset from CT. We shall be using a variant of this dataset for this problem. Each
student-entry in the dataset is represented as a dictionary. For example, one of the entries would look
like this:
Write a function named get_marks that accepts the scores_dataset and a variable
named subject as arguments. It should return the marks scored by all students in subject as a
list of tuples. Each element in this list is of the form (Name, Marks). The order in which the tuples
are appended to the list doesn't matter.
(1) You do not have to accept input from the user or print the output to the console. You just have to
write the definition of the function.
(2) Do not try to process the output produced. We randomly sample five elements from the list
returned by your function and print that in the desired form.
PPA 7
In this problem, we shall try to create the list of dictionaries which was given to us in the previous
problem.
Accept a positive integer n that represents the number of students in the class. n blocks of input
follow. Each block is made up of six lines and contains the details of one student in the class. Create a
dictionary corresponding to each student. All keys should be strings. The type of the value
corresponding to a key and the order in which the inputs should be accepted are shown in the table
given below.
Line number Key Type of Value
1 Name String
2 City String
3 SeqNo Integer
4 Mathematics Integer
5 Physics Integer
6 Chemistry Integer
Append each dictionary to a list named scores_dataset. This is the list that we will finally use
for evaluating your code. The dictionaries corresponding to the students should be appended in the
order in which they appear in the sequence of inputs.
n = int(input())
scores_dataset = [ ]
for i in range(n):
record = dict()
record['Name'] = input()
record['City'] = input()
record['SeqNo'] = int(input())
record['Mathematics'] = int(input())
record['Physics'] = int(input())
record['Chemistry'] = int(input())
scores_dataset.append(record)
PPA 8
Write the following functions:
(1) factors: accept a positive integer nn as argument. Return the set of all factors of nn.
(2) common_factors: accept two positive integers aa and bb as arguments. Return the set of
common factors of the two numbers. This function must make use of factors.
(3) factors_upto: accept a positive integer nn as argument. Return a dict D, whose keys are
integers and values are sets. Each integer in the range [1, n], endpoints inclusive, is a key of D. The
value corresponding to a key, is the set of all factors of key. This function must make use
of factors.
The idea we are trying to bring out here is to make use of pre-defined functions whenever needed.
1 def factors(n):
2 '''
3 Argument:
4 n: integer
5 Return:
6 factors_of_n: set
7 '''
8 pass
9
10def common_factors(a, b):
11 '''
12 Arguments:
13 a, b: integers
14 Return:
15 factors_common: set
16 '''
17 pass
18
19def factors_upto(n):
20 '''
21 Argument:
22 n: integer
23 Return:
24 result: dict (keys: integers, values: sets)
25 '''
You do not have to accept input from the user or print output to the console. You just have to write
the definition of all three functions. Each test case will correspond to one function call.
def factors(n):
F = set()
for i in range(1, n + 1):
if n % i == 0:
F.add(i)
return F
def factors_upto(n):
D = dict()
for i in range(1, n + 1):
D[i] = factors(i)
return D
PPA 9
Accept a sequence of words as input. Create a dictionary named real_dict whose keys are the
letters of the English alphabet. For each key (letter), the corresponding value should be a list of words
that begin with this key (letter). For any given key, the words should be appended to the
corresponding list in the order in which they appear in the sequence. You can assume that all words of
the sequence will be in lower case.
L = input().split(',')
real_dict = dict()
for word in L:
start = word[0]
if start not in real_dict:
real_dict[start] = [ ]
real_dict[start].append(word)
PPA 10
The scores dataset is a list of dictionaries one of whose entries is given below for your reference:
1 def group_by_city(scores_dataset):
2 '''
3 Argument:
4 scores_dataset: list of dicts
5 Return:
6 cities: dict: (key: string, value: list of strings)
7 '''
8
9 def busy_cities(scores_dataset):
10 '''
11 Argument:
12 scores_dataset: list of dicts
13 Return:
14 result: list of strings
15 '''
(1) You do not have to accept input from the user or print the output to the console. You just have to
write the definition of both the functions.
(2) Do not try to process the output produced. We randomly sample a few elements from the
dictionary or list returned by your function and print that in the desired form.
def group_by_city(scores_dataset):
cities = dict()
return cities
def busy_cities(scores_dataset):
cities = group_by_city(scores_dataset)
busy = [ ]
maxpop = 0
for city in cities:
if len(cities[city]) > maxpop:
maxpop = len(cities[city])
busy = [city]
elif len(cities[city]) == maxpop:
busy.append(city)
return busy
GrPA 1
The scores dataset is a list of dictionaries one of which is given below for your reference:
Write a function named get_toppers that accepts three arguments in this order:
• scores_dataset
• subject
• gender
It should a return a list of the names of students who belong to the gender given by the
argument gender ('F' or 'M') and have topped in the subject given by the argument subject. As
there could be multiple toppers, the function should return a list of names.
(2) Just to be clear, a topper is a student who has scored the maximum marks in the subject.
(3) You do not have to accept input from the user or print the output to the console. You just have to
write the definition of the function.
GrPA 2
Write a function named freq_to_words that accepts a list of words as argument. It should return a
dictionary which has the following structure:
• key: frequency of words in the list
• value: list of all words that have the above frequency
1 def freq_to_words(words):
2 '''
3 Argument
4 words: list of strings
5 Return:
6 result: dictionary
7 key: integer
8 value: list of strings
9 '''
words freq_to_words(words)
['a', 'random', 'collection', 'a', 'another', 'a', 'random'] {1: ['another', 'collection'], 2: ['random'], 3: ['a']}
def freq_to_words(words):
freq_dict = words_to_frequency(words)
result = dict()
for word in freq_dict:
freq = freq_dict[word]
if freq not in result:
result[freq] = [ ]
result[freq].append(word)
return result
GrPA 3
Write a function named rotate that accepts a matrix mat as argument. It should return a matrix that
is rotated by 90˚ in the clockwise direction. For example:
d a
a b c
[ ] → [ e b]
d e f
f c
1def rotate(mat):
2 '''
3 Argument:
4 mat: list of lists
5 Return:
6 rotated_mat: list of lists
7 '''
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
def rotate(mat):
#print(mat)
rotated=[]
for i in range(len(mat[0])):
turned=[]
for j in mat[::-1]:
#print(j[i])
turned.append(j[i])
rotated.append(turned)
return rotated
GrPA 4
Write a function named two_level_sort that accepts a list of tuples named scores as
argument. Each element in this list is of the form (Name, Marks) and represents the marks scored
by a student in a test: the first element is the student's name and the second element is his or her
marks.
The function should return a list of tuples that is sorted in two levels:
• Level-1: ascending order of marks
• Level-2: alphabetical order of names among those students who have scored equal marks
Each element in the returned list should also be of the form (Name, marks). Note that level-2
should not override level-1. That is, after the second level of sorting, the list should still be sorted in
ascending order of marks. Additionally, the students having the same marks should appear in
alphabetical order.
Sample input-output behaviour
scores two_level_sort(scores)
[('Harish', 80), ('Aparna', 90), ('Harshita', 80)] [('Harish', 80), ('Harshita', 80), ('Aparna', 90)]
[('Sachin', 85), ('Yuvan', 65), ('Anita', 85)] [('Yuvan', 65), ('Anita', 85), ('Sachin', 85)]
1def two_level_sort(scores):
2 '''
3 Argument:
4 scores: list of tuples, (string, integer)
5 Return:
6 result: list of tuples (string, integer)
7 '''
(1) You should not use any built-in sort functions to solve this problem.
(2) You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
def two_level_sort(scores):
sorted_L = [ ]
while scores != [ ]:
# minentry[0] -> name, minentry[1] -> score
minentry = scores[0]
for i in range(len(scores)):
# scores[i][0] -> name, scores[i][1] -> marks
if scores[i][1] < minentry[1]:
minentry = scores[i]
# If scores are equal, check for alphabetical order
elif (scores[i][1] == minentry[1] and
scores[i][0] < minentry[0]):
minentry = scores[i]
sorted_L.append(minentry)
scores.remove(minentry)
return sorted_L
Week 7
GrPA 1
A round-robin tournament is one in which each team competes with every other team. Consider a
version of the IPL tournament in which every team plays exactly one game against every other team.
All these games have a definite result and no match ends in a tie. The winning team in each match is
awarded one point.
Eight teams participate in this round-robin cricket tournament: CSK, DC, KKR, MI, PK, RR, RCB
and SH. You are given the details of the outcome of the matches. Your task is to prepare the IPL
points table in descending order of wins. If two teams have the same number of points, the team
whose name comes first in alphabetical order must figure higher up in the table.
There are eight lines of input. Each line is a sequence of comma-separated team names. The first team
across these eight lines will always be in this order: CSK, DC, KKR, MI, PK, RR, RCB and SH. For a
given sequence, all the other terms represent the teams that have lost to the first team. For example,
the first line of input could be: CSK,MI,DC,PK. This means that CSK has won its matches against the
teams MI, DC and PK and lost its matches against all other teams. If a sequence has just one team, it
means that it lost all its matches.
Print the IPL points table in the following format — team:wins — one team on each line. There
shouldn't be any spaces in any of the lines.
results = [ ]
for i in range(8):
L = input().split(',')
winner = L[0] # the first team is the winner
losers = L[1: ] # all these teams have lost to the winner
# we only need the number of wins and the winning team
results.append((winner, len(losers)))
table = [ ]
# two-level-sort
# refer GrPA-4 of week-6
# we first sort by points, then by name
while results != [ ]:
maxteam = results[0]
for i in range(len(results)):
team = results[i]
if team[1] > maxteam[1]:
maxteam = team
elif team[1] == maxteam[1] and team[0] < maxteam[0]:
maxteam = team
results.remove(maxteam)
table.append(maxteam)
GrPA 2
Two dictionaries D1 and D2 can be merged to create a new dictionary D that has the following
structure:
• Each key-value pair in D is present either in D1 or D2.
• Each key in D1 is also a key in D. Likewise, each in D2 is also a key in D.
• If a particular key is common to both D1 and D2, the value corresponding to this key in one
of the two dictionaries is retained in D.
You do not have to accept the input or print the output to the console. You just have to write the
function definition.
GrPA 3
Given a square matrix M and two indices (i, j), Mij is the matrix obtained by removing the ith row and
the jth column of M.
(1) You can assume that the number of rows in MM will be at least 33 in each test case.
(2) You do not have to accept input from the user or print the output to the console.
GrPA 4
You are given certain details of the trains that stop at a station. Your task is to store these details in a
nested dictionary.
The first line of input is n, the number of trains that stop at the station. n blocks of input follow. The
first line in each block corresponds to the train name. The second line in each block corresponds to m,
the number of compartments in the train. m lines of input follow. Each of these m lines has two values
separated by a comma: name of the compartment and number of passengers in it.
Your task is to create a nested dictionary named station_dict. The keys of the dictionary are
train names, the value corresponding to a key is another dictionary. The keys of the inner dictionary
are the compartment names in this train, the values are the number of passengers in each
compartment. For example:
1 {
2 'Mumbai Express': {
3 'S1': 10,
4 'S2': 20,
5 'S3': 30
6 },
7 'Chennai Express': {
8 'S1': 10,
9 'S2': 20,
10 'S3': 30
11 }
12 }
(1) The values of the compartments should be represented as integers and not as strings.
(2) You do not have to print the output to the console. Do not try to print the output that you observe
in the "Expected Output". You just have to process the input and create the
dictionary station_dict.
n=int(input())
station_dict={}
for i in range(n):
m=input()
a=int(input())
d={}
for i in range(a):
s=input().split(',')
d[s[0]]=int(s[1])
station_dict[m]=d
Week 8
PPA 1
Write a recursive function named triangular that accepts a positive integer n as argument and
returns the sum of the first n positive integers.
1def triangular(n):
2 '''
3 Argument:
4 n: integer
5 Return:
6 result: integer
7 '''
You do not have to accept input from the user or print the output to the console. You just have to
write the function definition.
def triangular(n):
if n == 1:
return 1
return n + triangular(n - 1)
PPA 2
The factorial of a positive integer n is defined as follows:
n!=1⋅2⋅3⋯n
Write a recursive function named factorial that accepts a positive integer nn as argument and
returns the factorial of n.
1def factorial(n):
2 '''
3 Argument:
4 n: integer
5 Return:
6 result: integer
7 '''
You do not have to accept input from the user or print the output to the console. You just have to
write the function definition.
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
PPA 3
Write a recursive function named multiply accepts two positive integers a and b as argument and
returns their product. You can only use + and − operators. You are not allowed to use the ∗ symbol
anywhere in your code!
PPA 4
The logarithm of a number x to the base 2 is the number of times 2 has to be multiplied with itself so
get x, and is denoted by log2(x). For example, log2(4)=2. Note that log2(1)=0.
Write a recursive function named logarithm that accepts a positive integer xx as argument and
returns log2(x).
1 def logarithm(x):
2 '''
3 Argument:
4 x: integer
5 Result:
6 result: integer
7 '''
def logarithm(x):
if x == 1:
return 0
return 1 + logarithm(x // 2)
PPA 5
Write a recursive function named palindrome that accepts a string word as argument and
returns True if it is a palindrome and False otherwise.
1def palindrome(word):
2 '''
3 Argument:
4 word: string
5 Return:
6 result: bool
7 '''
You do not have to accept input from the user or print the output to the console. You just have to
write the function definition.
def palindrome(word):
if len(word) <= 1:
return True
if word[0] != word[-1]:
return False
return palindrome(word[1:-1])
PPA 6
Consider a spiral of semicircles. We start at a point P0 on the x-axis with coordinates (l,0). The first
arm of the spiral ends at P1 with coordinates (r,0). The second arm of the spiral starts at P1 and ends at
the center of the first arm, P2. The third arm starts from P2 and ends at P3 which happens to be the
center of the second arm. And finally, the fourth arm starts at P3 and ends at P4, the center of the third
arm.
(1) Observe what happens as the value of n increases. Those who have taken Maths-2, can you try to
answer this question without using Python, just using the concept of limits that you have learned?
(2) You do not have to accept input from the user or print the output to the console. You just have to
write the function definition.
PPA 7
Write a recursive function named count that accepts the following arguments:
• L: list of words
• word: a word, could be any string
This function should return the number of occurrences of word in L.
(1) You cannot use the built-in count method for lists in this problem.
(2) All words will be in lower case.
(3) You do not have to accept input from the user or print the output to the console. You just have to
write the definition of both the functions.
def count(L, word):
if len(L) == 0:
return 0
if L[-1] == word:
return 1 + count(L[:-1], word)
else:
return count(L[:-1], word)
PPA 8
Write a recursive function named non_decreasing that accepts a non-empty list L of integers as
argument and returns True if the elements are sorted in non-decreasing order from left to right,
and False otherwise.
1def non_decreasing(L):
2 '''
3 Argument:
4 L: list of integers
5 Return:
6 result: bool
7 '''
You do not have to accept input from the user or print the output to the console. You just have to
write the function definition.
def non_decreasing(L):
if len(L) <= 1:
return True
if L[-2] > L[-1]:
return False
return non_decreasing(L[:-1])
PPA 9
Write a recursive function named uniq that accepts a non-empty list L as argument and returns a new
list after removing all duplicates from it. Your function must retain the last occurrence of each distinct
element in the list.
1def uniq(L):
2 '''
3 Argument:
4 L: list
5 Return:
6 result: list
7 '''
You do not have to accept input from the user or print the output to the console. You just have to
write the function definition.
def uniq(L):
if len(L) == 1:
return L
if L[0] in L[1: ]:
return uniq(L[1: ])
else:
return [L[0]] + uniq(L[1: ])
PPA 10
Write a recursive function named search that accepts the following arguments:
• L: a sorted list of integers
• k: integer
The function should return True if k is found in the list L, and False otherwise.
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
PPA 11
(1) Write a function named insert that accepts a sorted list L of integers and an integer x as
arguments. It should return a sorted list with the element x inserted into the input list at the right
place.
(2) Write a recursive function named isort that accepts a non-empty list L of integers as argument.
It should return a sorted list in ascending order. isort must make use of insert. This is a popular
sorting algorithm and is called insertion sort.
def isort(L):
if len(L) == 1:
return L
return insert(isort(L[: -1]), L[-1])
PPA 12
A polynomial is a mathematical function of the following form:
f(x)=a0x0+a1x1+a2x2+⋯+anxn
The ais are called the coefficients of the polynomial and uniquely determine it. This polynomial can
be represented in Python using a list of its coefficients:
L = [a0, a1, a2, . . ., an]
Note that L[i] corresponds to the coefficient ai of xi in f(x), for 0≤i≤n.
Write a recursive function named poly that accepts the list of coefficients L and a real
number x_0 as arguments. It should return the polynomial evaluated at the value x_0. For
example poly([1, 2, 3], 5) should return the value 1+2×5+3×52=86.
You do not have to accept input from the user or print the output to the console. You just have to
write the function definition.
PPA 13
Write a recursive function named power that accepts a square matrix A and a positive integer m as
arguments and returns Am.
You do not have to accept input from the user or print the output to the console. You just have to
write the function definition.
def zero_matrix(n):
'''zero matrix of size n x n'''
M = [ ]
for i in range(n):
row = [ ]
for j in range(n):
row.append(0)
M.append(row)
return M
PPA 14
Challenge Problem: If you have grasped the essence of recursion, then you would see the simplicity of
the whole idea when you solve this problem. All those who have done Maths-2, or are doing Maths-2,
should be able to appreciate this problem. If you are yet to do Maths-2, you can still try to attempt this
problem. But we request learners not to be intimidated by the heavy use of notation. Feel free to skip
this problem if you perceive it to be too hard.
Determinant
Any square matrix MM has a number associated with it called its determinant. The determinant of
a 2×2 matrix is defined as follows:
a b
det ([ ]) = ad-bc
c d
For any n×n square matrix M, its determinant is defined recursively as follows:
n-1
det(M) = ∑ (-1)j ∙ M[0][j] ∙ Mj
j=0
Here, Mj is the determinant of the matrix obtained by removing the 0th row and the jth column
of M for 0≤j<n. We have used zero-based indexing.
For example, for a 3×3 matrix, we have:
a b c
e f d f d e
det ([d e f ]) = (-1)0 ∙ a ∙ det ([ ]) + (-1)1 ∙ b ∙ det ([ ]) + (-1)2 ∙ c ∙ det ([ ])
h i g i g h
g h i
Write a recursive function named det that accepts a square matrix as argument and returns its
determinant. In the process of writing this function, it would be useful to look into GrPA-3 of week-7.
A good approach would be to write two functions: det and minor_matrix.
1def det(M):
2 '''
3 Argument:
4 M: list of lists
5 Return:
6 result: integer
7 '''
You do not have to accept input from the user or print the output to the console. You just have to
write the function definition.
return M_ij
def det(M):
n = len(M)
if n == 2:
return M[0][0] * M[1][1] - M[0][1] * M[1][0]
dsum = 0
for j in range(n):
dsum = dsum + M[0][j] * det(minor_matrix(M, j)) * ((-1) ** (j))
return dsum
PPA 15
You have a locker that has a finite number of coins in it. Each coin has some positive integer that is
engraved on it. This denotes how valuable the coin is. You wish to draw a subset of coins from the
locker whose total worth is ss. Your task is to determine if this can be done with the coins available in
your locker.
Write a recursive function named subset_sum that accepts a list of positive integers L and a
positive integer s as arguments. The list L represents the coins in your locker. The
integer s represents the total value of the coins that you need to withdraw. Return True if you can
withdraw some subset of coins whose combined worth is ss, return False otherwise.
GrPA 1
Write a recursive function named reverse that accepts a list L as argument and returns the reversed
list.
1def reverse(L):
2 '''
3 Arguments:
4 L: list, type of elements could be anything
5 Return:
6 result: list
7 '''
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
def reverse(L):
if len(L)==1:
return L
else:
return ([L[-1]]+reverse(L[:-1]))
GrPA 2
Write a recursive function named linear that accepts the following arguments:
• P: a non-empty list of positive integers
• Q: a non-empty list of positive integers
• k: a positive integer
It should return True only if both the conditions given below are satisfied:
• P and Q are of same length.
• P[i]=k⋅Q[i], for every integer i in the range [0,len(P)−1], endpoints inclusive.
Even if one of these conditions is not satisfied, it should return False.
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
def linear(P, Q, k):
if len(P) != len(Q):
return False
if len(P) == 0:
return True
if P[0] / Q[0] != k:
return False
return linear(P[1: ], Q[1: ], k)
GrPA 3
The Collatz function is defined for a positive integer n as follows.
3n + 1 if n is odd
f(n) = {
n/2 if n is even
We consider the repeated application of the Collatz function starting with a given integer nn, which
results in the following sequence:
f(n),f(f(n)),f(f(f(n))),…
It is conjectured that no matter which positive integer n you start from, the sequence will always
reach 1. For example, If n=10, the sequence is:
Seq No. n f(n)
1 10 5
2 5 16
3 16 8
4 8 4
5 4 2
6 2 1
Thus, if you start from n=10, you need to apply the function f six times in order to first reach 1.
Write a recursive function named collatz that accepts a positive integer n as argument,
where 1<n≤32,000, and returns the number of times f has to be applied repeatedly in order to first
reach 1.
1def collatz(n):
2 '''
3 Argument:
4 n: integer
5 Assume that 1 < n <= 32,000
6 Returns:
7 result: integer
8 '''
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
def collatz(n):
if n==2:
return 1
else:
if n%2!=0:
c=1+collatz((3*n)+1)
return c
else:
c=1+collatz(n/2)
return c
GrPA 4
Fibonacci
Fibonacci is a young resident of the Italian city of Pisa. He spends a lot of time at the premises of the
Leaning Tower of Pisa, one of the iconic buildings in the city, that is situated close to his home.
During all his visits to the tower, he plays a strange game while climbing the marble steps of the
tower.
The Game
Fibonacci likes to climb the steps either one at a time, two at a time or three at a time. This adds
variety to the otherwise monotonous task of climbing. He wants to find the total number of ways in
which he can climb n steps, assuming that the order of his individual steps matters. Your task is to
help Fibonacci compute this number.
For example, if he wishes to climb three steps, the case of n = 3, he could do it in four different ways:
• (1, 1, 1): do it in three moves, one step at a time
• (1, 2): do it in two moves, first take a single step, then a double step
• (2, 1): do it in two moves, first take a double step, then a single step
• (3): do it in just one move, directly leaping to the third step
To take another example, if n = 5, then some of the sequences could be:
(1, 3, 1), (1, 1, 3), (3, 1, 1), (2, 1, 1, 1), (1, 2, 1, 1), (2,1,2), (1,3,1), (1,1,3), (3,1,1), (2,1,1,1), (1,2,1,1),
(2,1,2)
Each sequence is one of the ways of climbing five steps. The point to note here is that each element of
a sequence can only be 1, 2 or 3.
Write a recursive function named steps that accepts a positive integer n as argument. It should
return the total number of ways in which Fibonacci can ascend n steps. Note that the order of his steps
is important.
1def steps(n):
2 '''
3 Argument:
4 n: integer
5 Return:
6 result: integer
7 '''
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
def steps(n):
if n==1 or n==0:
return 1
if n==2:
return 2
else:
return (steps(n-1)+steps(n-2)+steps(n-3))
GrPA 5
P is a dictionary of father-son relationships that has the following structure: for any key in the
dictionary, its corresponding value is the father of key. As an example:
1P = {
2 'Jahangir': 'Akbar',
3 'Akbar': 'Humayun',
4 'Humayun': 'Babur'
5}
If 'Jahangir' is the key, then the 'Akbar', his father, is the value. This is true of every key in
the dictionary.
Write a recursive function named ancestry that accepts the following arguments:
• P: dictionary of relationships
• present: name of a person, string
• past: name of a person, string
It should return the sequence of ancestors of the person named present, traced all the way back up
to person named past. For example, ancestry(P, 'Jahangir', 'Babur') should return
the list:
L = ['Jahangir', 'Akbar', 'Humayun', 'Babur']
In more Pythonic terms, L[i] is the father of L[i - 1], for 1≤i<len(L), with the condition
that L[0] should be present and L[-1] should be past.
(1) You can assume that no two persons in the dictionary have the same name. However, a given
person could either appear as a key or as a value in the dictionary.
(2) A given person could appear multiple times as one of the values of the dictionary. For example, in
test-case-2, Prasanna has two sons, Mohan and Krishna, and hence appears twice (as a value).
(2) You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
Week 9
PPA 1
Write a function named read_file that accepts a text file named filename as argument. Within
the function, read the file and print each line of the file on a separate line in the console. You shouldn't
print any extra characters at the end of a line. There shouldn't be an empty line between any two
consecutive lines.
1def read_file(filename):
2 '''
3 Argument:
4 filename: string, name of the file to be read
5 Return:
6 None
7 '''
(1) filename is a string variable that holds the name of the file. For example, in the first test case, it
is filename = 'public_1.txt'.
(2) You do not have to accept input from the console. You have to write the function definition and
print the contents of the file within the function.
def read_file(filename):
f = open(filename, 'r')
for line in f:
print(line.strip())
f.close()
PPA 2
Write a function named read_line that accepts a text file named filename and a positive
integer n as arguments. Within the function, read the file and return the nth line of the file. If
the file has fewer than n lines, return the string 'None'.
PT 1.1
Print the following pattern. There is exactly one space between any
two consecutive numbers on any line. There are no spaces at the end
of any line.
121
12321
1234321
123454321
print('1 2 1')
print('1 2 3 2 1')
print('1 2 3 4 3 2 1')
print('1 2 3 4 5 4 3 2 1')
PT 1.2
A simple algorithm has to be designed to find out whether a student
belongs to the Data Science branch or not. The input will be a
student's roll number, which is of the form BR18B0000.
Here, BR represents the branch code, 18 represents the year of
joining, B represents the education level and 0000 represents the
specific identification given to the student of that batch. The branch
code for Data Science is DS. Print True if the student belongs to
Data Science branch and False otherwise.
s = input()
if s[0]=='D' and s[1]=='S':
print("True")
else:
print("False")
PT 1.3
The police are trying to track a criminal based on the evidence
available at a crime site. Their main clue is a vehicle's damaged
number plate. Only the string TN07 is visible. The format of the
registration number is AA00AA00, where the first two letters are
alphabets, next two are numbers, next two are again alphabets
followed by two numbers at the end. A number plate is picked from a
database of registration numbers and is given to you as input. Your
task is to determine if this could belong to the criminal or not.
Print True if the number plate
contains TN07 and False otherwise.
n=input()
if (n[0:4]=='TN07') or (n[4:8]=='TN07'):
print('True')
else:
print('False')
PT 1.4
Accept two integers a and b as input and print the absolute
difference of both the numbers. For example, if a = 9, b = 8, then
the absolute difference is 9 - 8 = 1. So, your output should be 1.
You should be able to solve this problem using the concepts covered
in this week.
a=int(input())
b=int(input())
print(abs(a-b))
PT 1.5
You are given a string and two non-negative integers as input. The
two integers specify the start and end indices of a substring in the
given string. Create a new string by replicating the substring a
minimum number of times so that the resulting string is longer than
the input string. The input parameters are the string, start index of
the substring and the end index of substring (endpoints inclusive)
each on a different line.
n=input()
a=int(input())
b=int(input())
x=n[a:b+1]
y=len(n)
ans=""
while(y>=len(ans)):
ans+=x
print(ans)
PT 2.1
A class teacher has decided to split her entire class into four groups, namely Sapphire, Peridot, Ruby,
and Emerald for sports competitions. For dividing the students into these four groups, she has
followed the pattern given below:
All the students are represented by their roll numbers. Based on the above pattern, given the roll
number as input, print the group the student belongs to. Note that the roll number can be any
positive integer and not necessarily less than 25.
n=int(input())
for i in range(1,n+1,4):
if n==i:
print('Sapphire')
for j in range(2,n+1,4):
if n==j:
print('Peridot')
for k in range(3,n+1,4):
if n==k:
print('Ruby')
for l in range(4,n+1,4):
if n==l:
print('Emerald')
PT 2.2
A data science company wants to hire data scientists from IIT Madras.
The company follows a certain criteria for selection: for a student to
be selected, the number of backlogs should be at most 5 and the
CGPA (Cumulative Grade Point Average) should be greater than 6. If
the student does not fit the above criteria, then the student is not
offered the job. If the student is selected, then the salary offered is
equal to 5 times his/her CGPA (in lakhs).
Accept the number of backlogs (integer) and the CGPA (float) of the
student as input. Your task is to determine if the student is selected or
not. If the student is selected, then print the package. If not, then
print the string Not Selected.
a=float(input())
b=float(input())
if a<=5 and b>6:
print(5*b)
else:
print('Not Selected')
PT 2.3
A test match happened between Team A and Team B. The scores of the teams in both the innings are
given as input in eight lines in the format given below. The first two lines represent the scores of
Team A in the first innings and the next two lines represent the scores of Team A in the second
innings. Likewise, the last four lines represent the scores of Team B in both the innings.
The numbers in 2nd, 4th, 6th, and 8th lines represent the wickets lost by the teams and the numbers in
1st, 3rd, 5th, and 7th represent the runs scored.
120
10
210
10
115
10
189
10
In the above example, team-A has scored 120 for the loss of 10 wickets in the first innings, and 210
for the loss of 10 wickets in the second innings. Team A plays first and Team B plays second. Your
task is to determine the winner of the match.
Process to decide the outcome
Team A wins if and only if the sum of its scores in both the innings is greater than sum of the scores
of Team B in both the innings AND Team B lost all the ten wickets in the second innings. Team B
wins if the sum of its scores in both the innings is greater than sum of the scores of Team A in both
the innings.
A match will end in a draw if the sum of scores in the two innings of both the teams are
equal OR if Team B did not lose all the ten wickets in the second innings. If the match ends in a
draw, then print DRAW.
Example
120
10
210
10
115
10
189
10
Example output
Team A
120 + 210 > 115 + 89 and Team B lost all 10 wickets in second innings, therefore Team A is the
winner of the test match.
a=int(input())
b=int(input())
c=int(input())
d=int(input())
e=int(input())
f=int(input())
g=int(input())
h=int(input())
if a+c>e+g and h==10:
print('Team A')
elif a+c<e+g:
print('Team B')
else:
print('DRAW')
PT 2.4
A word is said to be perfect if it satisfies all the following criteria:
(1) All the vowels (a,e,i,o,u) should be present in the word.
(2) Let the vowels be represented as v1=a, v2=e, v3=i, v4 = o, v5=u in lexical order.
• If i<j, then the first appearance of vi in the word should come before the first appearance
of vj.
• If i<j, then the count of vi should be greater than or equal to the count of vj.
Accept a word as input. Print It is a perfect word. if the word is perfect, else print It is
not a perfect word.
s=input()
a='aeiou'
f1=True
for i in range(5):
if a[i] not in s:
f1=False
break
if f1:
if s.index('a')<s.index('e')<s.index('i')<s.index('o')<s.index('u'):
if
s.count('a')>=s.count('e')>=s.count('i')>=s.count('o')>=s.count('u'):
print('It is a perfect word.')
else:
print('It is not a perfect word.')
else:
print('It is not a perfect word.')
PT 2.5
Accept four integers as input and write a program to print these integers in non-decreasing order.
The input will be four integers in four lines. The output should be a single line with all the integers
separated by a single space in non-decreasing order.
Note: There is no space after the fourth integer.
a=int(input())
b=int(input())
c=int(input())
d=int(input())
x=[a,b,c,d]
x.sort()
print(x[0],x[1],x[2],x[3])
PT 3.1
Accept a string as input and print PALINDROME if it is a
palindrome, and NOT PALINDROME otherwise.
string=input()
if(string==string[::-1]):
print("PALINDROME")
else:
print("NOT PALINDROME")
PT 3.2
Two integers are co-prime if the only divisor common to them is one.
Accept two distinct positive integers as input in two different lines.
Print Coprime if the two integers are co-prime, else print Not
Coprime. Assume that both the integers are greater than two.
def are_coprime(a,b):
hcf = 1
return hcf == 1
first = int(input())
second = int(input())
if are_coprime(first, second):
print('Coprime')
else:
print('Not Coprime')
PT 3.3
Accept a string as input, print Integer if the string is an integer,
print Float if it a float, else print None.
n=input()
if '.'in n and n.count('.')==1:
n=n.replace('.','')
if n.isnumeric():
print('Float')
else:
print('None')
elif n.isnumeric():
print('Integer')
else:
print('None')
PT 3.4
Multiple Select Questions (MSQ) could have more than one correct answer. The marks scored by a
student in a MSQ will be determined by the following conditions:
(1) If the question has c correct options, each individual correct option carries = marks
(2) If a student selects any of the wrong options, the marks awarded for the question will be 0.
Calculate the marks obtained by the student and print this as float value.
(2) Second line contains the number of options for the question.
(3) Third line is a comma-separated sequence of correct options for this question.
Note: Options are numbered using positive integers in the range [1, 9], endpoints inclusive. A
question will have at most nine options. The number of marks and the correct options will always be
integers.
If the question has five options in total, then the options will be numbered as 1,2,3,4,5.
marks = int(input())
options = int(input())
correct_options = input().split(',')
answered_options = input().split(',')
c = 0
for i in answered_options:
if i in correct_options:
c += 1
else:
c = 0
break
marks_per_option = marks / len(correct_options)
total_marks = marks_per_option * c
print(total_marks)
PT 3.5
Consider two non-empty strings a and b of lengths n1 and n2 respectively, which contain only
numbers as their characters. Both the strings are in ascending order, that is a[i]≤a[j] for 0≤i<j<n1. The
same holds true for b. You need to merge both the strings into one string of length n1+n2 such that all
the characters of this combined string are also in ascending order.
Accept a and b as input and print this merged string as output.
n=input()
s=input()
t=s+n
m=''
w='0123456789'
for i in range(len(w)):
for j in range(len(t)):
if t[j]==w[i]:
m+=w[i]
print(m)
PT 4.1
You are given a list of strings. Where each string contains two integers that are comma
separated. For each of the string, you need to check whether the given two integers in string
are co-prime or not. You need to print list of values as YES or NO for each value of the list
separated by comma. Print YES if the pair of integers are co-prime else print NO.
n = int(input())
A=[]
for i in range(n):
A.append(input().split(','))
for j in range(2):
A[-1][j] = int(A[-1][j])
def factors(n):
l=[]
for i in range(1,n+1):
if n%i==0:
l.append(i)
l=set(l)
return l
x=[]
for i in A:
if factors(i[0])&factors(i[1])=={1}:
x.append('YES')
else:
x.append('NO')
print(*x,sep=',')
PT 4.2
The first line of input contains a positive integer n. The second line of input contains a sequence of
comma-separated positive integers. Print the minimum number of terms that need to be picked up
from the sequence so that the sum of these terms is greater than or equal to n. If no such minimum
number exists, then print the string None.
(1) For example, if the input is 100 and the sequence is 10,88,3,4,99, then the minimum number of
terms we need to pick up is 2 so that their sum is greater than or equal to 100.
(2) If the input is 99 and the sequence is 10,20,5,18,17, then we can never get a sum that is greater
than or equal to 99, no matter how many numbers we pick up. So, the output here is None.
a=int(input())
b=input().split(',')
total=0
count=0
for i in range(len(b)):
total =total+int(b[i])
count+=1
if total >=a:
print(count)
break
else:
print('None')
PT 4.3
Two strings are said to be equivalent if either string can be obtained by rearranging the characters of
the other string. For example, good and odog are equivalent. But apple and lape are not equivalent.
Accept two strings as input. Print Equivalent if both the strings are equivalent and Not
Equivalent otherwise.
s1=input()
s2=input()
flag=True
if len(s1)==len(s2):
for i in s1:
if s1.count(i)!=s2.count(i):
print('Not Equivalent')
flag=False
break
if flag:
print('Equivalent')
else:
print('Not Equivalent')
PT 4.4
A is a square matrix of size n×n that is given to you. m is a positive integer that is also
given to you. Print the value of Am.
n = int(input())
m = int(input())
A=[]
for i in range(n):
A.append(input().split(','))
for j in range(n):
A[-1][j] = int(A[-1][j])
B=A
for x in range(m-1):
t=[]
for i in range(n):
y=[]
for j in range(n):
c=0
for k in range(n):
c+=A[i][k]*B[k][j]
y.append(c)
t.append(y)
B=t
print(B)
PT 5.1
A function f(n) is defined as f(n)= 1∗3∗5∗7∗⋯∗n−1/2∗4∗6∗8∗10∗⋯∗n if n is even, and f(n)=
1∗3∗5∗7∗⋯∗n/2∗4∗6∗8∗10∗⋯∗n−1 if n is odd. Assume that n is a positive integer. Given a
value of n as input, write a function named func to return the value of f(n). Value of f(1) is
1.
def func(n):
if n==1:
return 1
c=1
for i in range(1,n+1):
if i%2==1:
c*=i
else:
c/=i
return c
PT 5.2
In a portal login website, you are asked to write a function get_password_strength to decide
the strength of a password. The strength is decided based on the total score of the password, Use
following conditions:
1) If password has length greater than 7 then score increases by one point.
2) If password has at least one upper case and one lower case alphabets score increases by one point.
3) If password has at least one number and no consecutive numbers like 12 or 234 then score
increases by one point.
4) If password has at least one special character (any character other than numbers and alphabets) then
score increases by one point.
5) If password contains username, then it is invalid password.
If the password has score of four points, three points, two points, or one point then print Very
Strong, Strong, Moderate, or Weak respectively. If the password is invalid, then
print PASSWORD SHOULD NOT CONTAIN USERNAME and If the score is zero, then print Use a
different password.The arguments to the function are username and password which are
already defined.
def get_password_strength(username,password):
c=0
capital='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
c_flag=False
small='abcdefghijklmnopqrstuvwxyz'
s_flag=False
num='0123456789'
n_flag=False
nc_flag=True
if username in password:
print('PASSWORD SHOULD NOT CONTAIN USERNAME')
return
if len(password)>7:
c=c+1
for i in range(len(password)):
if password[i] in small:
s_flag=True
elif password[i] in capital:
c_flag=True
elif password[i] in num:
n_flag=True
if n_flag:
if i!=(len(password)-1):
if num[((num.index(password[i]))+1)]==password[i+1]:
nc_flag=False
if c_flag and s_flag :
c+=1
if n_flag and nc_flag:
c+=1
if not password.isalnum():
c+=1
if c==4:
print('Very Strong')
return
if c==3:
print('Strong')
return
if c==2:
print('Moderate')
return
if c==1:
print('Weak')
return
if c==0:
print('Use a different password')
return
ProgQuiz-M1
A data entry operator has a faulty keyboard. The keys 0 and 1 are very unreliable. Sometimes they
work, sometimes they don't. While entering phone numbers into a database, the operator uses the
letter 'l' as a replacement for 1 and 'o' as a replacement for 0 whenever these binary digits let him
down. Both 'l' and 'o' are in lower case.
Accept a ten-digit number as input. Find the number of places where the numbers 0 and 1 have been
replaced by letters. If there are no such replacements, print the string No mistakes. If not, print the
number of mistakes (replacements) and in the next line, print the correct phone number.
n=input()
o=n.count('o')
l=n.count('l')
if o!=0:
for j in range(o):
n=n.replace('o','0')
if l!=0:
for j in range(l):
n=n.replace('l','1')
if o+l==0:
print('No mistakes')
else:
print(o+l,'mistakes')
print(n)
ProgQuiz-M2
A sequence of integers of even length is said to be left-heavy if the sum of the terms in the left-
half of the sequence is greater than the sum of the terms in the right half. It is termed right-
heavy if the sum of the second half is greater than the first half. It is said to be balanced if both
the sums are equal.
Accept a sequence of comma-separated integers as input. Determine if the sequence is left-
heavy, right-heavy or balanced and print this as the output.
l=input().split(',')
n=(len(l)//2)
left=0
right=0
for i in range(n):
left+=int(l[i])
right+=int(l[-(i+1)])
if left>right:
print('left-heavy')
elif left<right:
print('right-heavy')
elif left==right:
print('balanced')
ProgQuiz-M3
A square matrix M is said to be:
• diagonal: if the entries outside the main-diagonal are all zeros
• scalar: if it is a diagonal matrix, all whose of diagonal elements are equal
• identity: if it is a scalar matrix, all of whose diagonal elements are equal to 1
Accept a matrix M as input from the console. The first line of input will have n, the number of rows in
the matrix. Each of the next n lines will be a sequence of comma-separated integers that stands for
one row of the matrix.
Your task is to output the type of matrix and should be one of these
strings: diagonal, scalar, identity, non-diagonal. The type you output should be the
most appropriate one for the given matrix.
n=int(input())
mat=[]
a=True
b=True
c=True
for i in range(n):
t=[]
t=input().split(',')
for j in range(n):
t[j]=int(t[j])
mat.append(t)
for i in range(n):
for j in range(n):
if i!=j:
if mat[i][j]!=0:
a=False
if mat[i][i]!=mat[j][j]:
b=False
if mat[i][i]!=1:
c=False
if a and b and c:
print('identity')
elif a and b:
print('scalar')
elif a:
print('diagonal')
else:
print('non-diagonal')
ProgQuiz-M4
There are five boxes arranged from left to right. You keep adding a variable number of coins
sequentially in each box. Start from box-1 and keep going right. Once you reach the last box, head
back to box-1 and then keep adding coins. In any given turn, the number of coins added to a box is
always less than 10.
Find the box which has the maximum number of coins. If there are two boxes which have the same
maximum number of coins, output the smaller of the two box numbers. The sequence of coins is
represented by a string. For example, if the input is 3972894910, this is how coins are added:
Box Coins
1 3 + 9 = 12
2 9 + 4 = 13
3 7 + 9 = 16
4 2+1=3
5 8+0=8
In this case, 3 is the output as box-3 has the maximum number of coins in it.
a=int(input())
for i in range(1,a+1):
if a%i==0:
if i<=(a/i):
print(i,int(a/i),sep=(','))
ProgQuiz-M6
Sort a list L of items in non-decreasing order and store it in the list sorted_L. All items in the list
are of the same type. This common type could be int, float or str. The list L is already given to
you.
(1) You must write your solution within the function. Indent all your code by four spaces.
(2) You don't need to accept the input or print the output to the console.
(3) You are not allowed the use of built-in sort functions.
def sort(L):
# Enter your code below this line
# Indent all your code by four spaces
for i in range(len(L)):
for j in range(i,len(L)):
if L[i]>=L[j]:
L[i],L[j]=L[j],L[i]
sorted_L=L
# Enter your code above this line
# Indent all your code by four spaces
return sorted_L
PQuiz-1
Accept a positive integer n as input and find the print the smallest integer that is divisible by
all the integers in the range [1,n], endpoints inclusive.
n=int(input())
c=1
while 1:
flag=True
for i in range(1,n+1):
if c%i==0 and c!=i:
continue
else:
flag=False
break
if flag:
print(c)
break
c=c+1
PQuiz-2
Consider a sequence of words. A sub-sequence is a subset of consecutive words in this sequence. For
example, given the following sequence:
one,two,order,real,long,tight,tree,cool,lot,trouble
The following are some sub-sequences:
(1) one,two,order
(2) real,long,tight,tree
(3) cool
(4) one,two,order,real,long,tight,tree,cool,lot,trouble
Note that one,lot does not form a sub-sequence as far as this problem is concerned. (3) and (4) are
valid sub-sequences even though they are quite trivial in nature.
A sub-sequence is said to have the antakshari property if the last letter of every word in the sub-
sequence is equal to the first letter in the next word. For example, in the above sequence, we have the
following sub-sequences with this property:
1cool,lot
2cool,lot,trouble
3two,order,real
4two,order,real,long
Your task is to find the length of the longest sub-sequence with the antakshari property. In the above
sequence, the longest sub-sequence with this property has length 4.
Accept a sequence of comma separated words as input and print the length of the longest sub-
sequence with the antakshari property. All words in the sequence will be in lower case.
l=input().split(',')
c=1
maxi=1
for i in range(len(l)):
if i!=(len(l)-1):
if l[i][-1]==l[i+1][0]:
c=c+1
if c>maxi:
maxi=c
else:
if c>maxi:
maxi=c
c=1
else:
c=1
print(maxi)
PQuiz-3
This problem is about reversing a square matrix along row or column.
Reversing a matrix along the rows is to perform the following operation:
a00 a01 a02 a22 a21 a22
row
[a10 a11 a12 ] → [a10 a11 a12 ]
a20 a21 a22 a00 a01 a02
Reversing a matrix along the columns is to perform the following operation:
a00 a01 a02 a02 a01 a00
column
[a10 a11 a12 ] → [a12 a11 a10 ]
a20 a21 a22 a22 a21 a00
The first line of the input will be an integer n, which denotes the dimension of the square matrix. Each
of the next n lines in the input will have a sequence of n comma-separated integers. The last line in
the input will be one of these two words: row or column. If it is row, then reverse the matrix along
the row, else, reverse it along the column.
Print the reversed matrix as output: each line should contain one row of the matrix as a sequence of
comma-separated integers.
n=int(input())
mat=[]
for i in range(n):
a=input().split(',')
for j in range(n):
a[j]=int(a[j])
mat.append(a)
s=input()
final_mat=[]
if s=='row':
for i in range(n-1,-1,-1):
a=[]
for j in range(n):
a.append(mat[i][j])
final_mat.append(a)
if s=='column':
for i in range(n):
a=[]
for j in range(n-1,-1,-1):
a.append(mat[i][j])
final_mat.append(a)
for i in range(n):
for j in range(n):
if j!=n-1:
print(final_mat[i][j],end=',')
else:
print(final_mat[i][j])
PQuiz-4
A string str_1 is a substring of another string str_2, if str_1 is present as a sequence of
consecutive characters in str_2. For example, got is a substring of gottingen,
whereas got is not a substring of goat.
Accept a sequence of comma separated words as input. Print that word in the sequence which is a
substring of every other word in the sequence.
If you do not find any word that is a common substring of all words in the sequence, print None.
Assume that all the words will be in lower case.
def subset(s,word):
for i in s:
if word not in i:
return False
return True
s=input().split(',')
flag=True
for i in range(len(s)):
if subset(s,s[i]):
print(s[i])
flag=False
break
if flag:
print('None')
PQuiz-5
A number is called a double palindrome if both the number and its square are palindromes.
For example, 11 is double palindrome as both 11 and 121 are palindromes. Accept a
positive integer n as input and print all the double palindromes less than or equal to n in
ascending order.
n=input()
l=[]
a=1
while a<=int(n):
p1=False
r=''
k=''
j=a**2
a=str(a)
j=str(j)
m=len(a)
z=len(j)
for i in range(m-1,-1,-1):
r+=a[i]
if a==r:
p1=True
if p1:
for i in range(z-1,-1,-1):
k+=j[i]
if j==k:
l.append(a)
a=int(a)
a+=1
for i in range(len(l)):
print(l[i])
PQuiz-6
Three rectangular matrices A, B and C are provided to you. You need to compute the product of these
three matrices: A×B×C. Store the results of this matrix multiplication in a matrix named as prod.
Each of these matrices is a list of lists.
You do not have to accept input from the console or print the output to the console. You just have to
write your code within the function provided. Make sure to indent all your code by four spaces.
ProgQuiz-2-M1
para is a sequence of space-separated words. All words will be in lower case. There will be a single
space between consecutive words. The string has no other special characters other than the space.
Write a function named exact_count that accepts the string para and a positive integer nn as
arguments. You have to return True if there is at least one word in para that
occurs exactly nn times, and False otherwise.
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
ProgQuiz-2-M2
Your task is to do simple word problems such as this:
one plus two plus three
The answer is 6.
Accept a sequence of space-separated words as input. Each word is either a digit from "zero" to "nine"
(endpoints inclusive) or one of the two operands: "plus" or "minus". The operands and operators
alternate in the sequence. In other words, no two consecutive words will be of the same type.
You have to find the solution of this arithmetic problem and print the answer as an integer. Evaluate
the expression without introducing brackets anywhere. That is,
l=input().split(' ')
sum=0
c=1
d={'zero':0,'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eig
ht':8,'nine':9}
for i in l:
if i=='minus':
c=-1
continue
if i=='plus':
c=1
continue
sum=sum+(c*d[i])
print(sum)
ProgQuiz-2-M3
The price of a steel rod is generally a simple function of its length. However, requirements of
companies also influence the price. If you are selling rods to a company that has a preference for short
rods and doesn't use too many long rods, the price distribution could look like this:
Rod-length Price
1 10
2 20
3 20
4 5
5 3
If you have a rod of length 5 meters, you would make a lot more money by cutting the rod and selling
it as two rods — one of length 3 meters and another of length 2 meters — than selling a single rod of
length 5 meters.
Your task is to accept the length of a rod and the price distribution as inputs. You are allowed to make
at most one cut of the rod. Find the maximum revenue that you can obtain. Assume that you can only
sell rods of integer lengths.
First line of input is the length of the rod, L. The second line is a sequence of L comma separated
integers that corresponds to the selling prices of rods of lengths (1,2,3,⋯,L−1,L). Print the maximum
revenue that can be obtained with at most one cut of the given rod.
n=int(input())
l=input().split(',')
p=[]
max=0
for i in range(len(l)):
for j in range(len(l)):
s=0
if i+j==(n-2):
s=int(l[i])+int(l[j])
p.append(s)
p.append(int(l[-1]))
for i in range(len(p)):
if p[i]>max:
max=p[i]
print(max)
ProgQuiz-2-M4
Write a recursive function named subsets that accepts a non-empty list of distinct integers L as
argument. It should return the list of all subsets of L.
(1) Each subset is to be represented as a list of numbers.
(2) The order in which you arrange the elements within a subset doesn't matter. For L = [1, 2, 3], [1,
3] and [3, 1] represent the same subset.
(3) The order in which you append the subsets to the returned list doesn't matter.
(4) The empty list is a subset for all lists.
1def subsets(L):
2 '''
3 Argument:
4 L: list of integers
5 Return:
6 result: list of lists
7 '''
You do not have to accept input from the console or print output to the console.
def subsets(L):
if len(L) == 1:
return [[],L]
else:
l = []
for sub in subsets(L[0:-1]):
l.append(sub)
l.append([L[-1]])
l.append(sub+[L[-1]])
t=[]
for i in l:
if i not in t:
t.append(i)
return t
ProgQuiz-2-M5
Consider an irrational number in the following form:
𝑎 + 𝑏√𝑝
a,b and p are integers. Additionally, p is a prime. For all n≥1, it is known that there is a unique tuple
of integer (x,y,p) such that:
n
(𝑎 + 𝑏√𝑝) = x + y√𝑝
For example:
2
(2 + 3√5) = 49 + 12√5
Write a function named compute that accepts the integers a, b, p and n as arguments and returns a
tuple of integers (x,y).
You do not have to accept input from the user or print output to the console. You just have to write
the function definition.
The grid-world is represented as a matrix of strings: 'B' stands for the initial position of the ant, 'W'
stands for an empty cell and 'G' stands for the food source. For example, the grid-world on the left is
represented as:
W W W W G
W W W W W
W B W W W
W W W W W
[W W W W W]
Write a function named is_reachable that accepts a n \times nn×n matrix of strings
named grid as argument. Return (True, steps) if the ant can reach the food source,
where steps is the number of steps the ant needs to take. If it can't reach the food source,
return (False, None)
1def is_reachable(grid):
2 '''
3 Argument:
4 grid: matrix of strings (upper-case characters)
5 Return:
6 result: tuple, either (True, int) or (False, None)
7 '''
You do not have to accept the input from the user or print output to the console.
def is_reachable(grid):
n=len(grid)
for i in range(n):
for j in range(n):
if grid[i][j]=='B':
ib=i
jb=j
if grid[i][j]=='G':
ig=i
jg=j
if ib>=ig and jb<=jg:
a=(ib-ig)+(jg-jb)
return ((True,a))
else :
return ((False,None))