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

Practice Questions Python

The document contains 20 multiple choice questions related to Python programming. The questions cover topics like loops, functions, lists, strings and more. For each question, 4 options are given as possible answers and only one is the correct output of the code provided in the question.

Uploaded by

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

Practice Questions Python

The document contains 20 multiple choice questions related to Python programming. The questions cover topics like loops, functions, lists, strings and more. For each question, 4 options are given as possible answers and only one is the correct output of the code provided in the question.

Uploaded by

Om Mahajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Q1.

Given the following four patterns,

Pattern A Pattern B Pattern C Pattern D


1 12345 1 12345
12 1234 21 1234
123 123 321 123
1234 12 4321 12
12345 1 54321 1

Which of the pattern is produced by the following code?

a) Pattern A
b) Pattern B
c) Pattern C
d) Pattern D

Q2. What is the output of the following code:

lst=[3,4,6,1,2]
lst[1:2]=[7,8]
print(lst)

a) [3, 7, 8, 6, 1, 2]
b) Syntax error
c) [3, [7,8],6,1,2]
d) [3,4,6,7,8]
Output: [3, 7, 8, 6, 1, 2]

Q3. What is the output of the following code:


def fn(x):

x += [1]

mylist = [1, 2, 3, 4,7,87,83]

fn(mylist)

print(len(mylist))
a) 1
b) 7
c) 9
d) 8
Output: 8

Q4.
What is the output of the following code:
def f(i, values = []):
values.append(i)

return values

f(1)
f(2)
v = f(3)
print(v)
a) [1] [2] [3]
b) [1] [1, 2] [1, 2, 3]
c) [1, 2, 3]
d) 1 2 3
Output: [1, 2, 3]

Q5. The correct way to get the length of a List in Python:


a) len(mylist)
b) length(mylist)
c) mylist.count()
d) count(mylist)
Q6 Given a list
L=[10,20,30,40,50,60,70]
What would L[2:-2] return?
a) [10, 20, 30, 40]
b) [20, 30, 40, 50]
c) [20, 30, 40]
d) [30, 40, 50]

Q7 i=0

while i < 5:
print(i)
i += 5
if i==3:
continue
break
What will be the output of this statement?

a. 0
b. 0 5
c. 0 5 10 15
d. 0 0 5 5

Q8 func = lambda x: return x

print(func(2))

What will be the output of the following code

a. 2
b. 2.0
c. Syntax Error
d. 0
Q9 a=[0,11,22,33,44,55,66,77,88,99]
a[7:2:-1]
Identify Output
a. [77, 66, 55, 44, 33]
b. [44,33,22,11,0]
c. [99,88,77,66,55]
d. [0,11,22,33,44]
Q10 def main():
arg=4
square(arg)
print(arg)
def square(n):
n*=n
main()
What is the ouput?
a. 4
b. 16
c. 80
d. 25

1. What will be the output of the following Python code?

i=0
while i < 6:
print(i)
i += 1
else:
print(1)
a) 0 1 2 3 4 5 1
b) 0 1 2 1 0
c) 0 1 2 1
d) error

2. What will be the output of the following Python code?

x = " pqrcef"
while i in a:
print(i, end=" ")
a) p q r c e f
b) pqrcef
c) Error
d) i i i i i i …

3. What will be the output of the following Python code?

def Person(message, times = 1):


print(message * times)
Person('Aman')
Person('Niya', 5)
a) Aman
Niya, Niya, Niya, Niya, Niya
b) Aman
Niya 5
c) Aman
Niya, Niya, Niya, Niya, Niya
d) Aman
NiyaNiyaNiyaNiyaNiya

4. Which one of the following is a valid Python if statement:


a) if a>=2 :
b) if (a >= 2)
c) if (a => 22)
d) if a >= 22
5. What is the output of the following list operation

aList = [10, 20, 30, 40, 50, 60, 70, 80]

print(aList[2:5])

print(aList[:4])

print(aList[3:])

a) [20, 30, 40, 50]

[10, 20, 30, 40]

[30, 40, 50, 60, 70, 80]

b) [30, 40, 50]

[10, 20, 30, 40]

[40, 50, 60, 70, 80]

c) [20,30,40,50]

[10,20,30,40]

[40,50,60,70]

d) None of these

6. What is the output of the following list assignment

aList = [4, 8, 12, 16]

aList[1:4] = [20, 24, 28]

print(aList)

a) [4, 20, 24, 8, 12, 16]

b) [4, 20, 24, 28]


c) [4, 20, 24, 28, 8, 12, 16]

d) [4,4,12,16]

7. Select all the correct options to join two lists in Python

listOne = ['a', 'b', 'c', 'd']

listTwo = ['e', 'f', 'g']

a) newList = listOne + listTwo

b) newList = extend(listOne, listTwo)

c) newList = listOne.extends(listTwo)

d) newList.extend(listOne, listTwo)

8. n = 1

for i in range(1, 11, 2):

product = n * i
print(product)
a. 1
3
5
7
9
b. 2
6
4
8
10
c. 2
4
6
8
10
d. Infinite loop

9. What will be the output of the following Python code?


i=2
while True:
if i%4 == 0:
break
print(i)
i += 1
a)1 2 3
b) error
c) 2 3
d) none of the mentioned

10. A new element is added to the list using the command?


a) list1.addEnd(1)
b) list1.addLast(1)
c) list1.append(1)
d) list1.add(1)

11. What will be the output of the following Python code?

i=0
while i < 6:
print(i)
i += 1
else:
print(1)
a) 0 1 2 3 4 5 1
b) 0 1 2 1 0
c) 0 1 2 1
d) error

12. What will be the output of the following Python code?

x = " pqrcef"
while i in a:
print(i, end=" ")
a) p q r c e f
b) pqrcef
c) Error
d) i i i i i i …

13. What will be the output of the following Python code?

def Person(message, times = 1):


print(message * times)
Person('Aman')
Person('Niya', 5)
a) Aman
Niya, Niya, Niya, Niya, Niya
b) Aman
Niya 5
c) Aman
Niya, Niya, Niya, Niya, Niya
d) Aman
NiyaNiyaNiyaNiyaNiya

14. Which one of the following is a valid Python if statement:


e) if a>=2 :
f) if (a >= 2)
g) if (a => 22)
h) if a >= 22

15. What is the output of the following list operation

aList = [10, 20, 30, 40, 50, 60, 70, 80]

print(aList[2:5])

print(aList[:4])

print(aList[3:])

e) [20, 30, 40, 50]

[10, 20, 30, 40]

[30, 40, 50, 60, 70, 80]

f) [30, 40, 50]

[10, 20, 30, 40]

[40, 50, 60, 70, 80]

g) [20,30,40,50]

[10,20,30,40]

[40,50,60,70]

h) None of these

16. What is the output of the following list assignment


aList = [4, 8, 12, 16]

aList[1:4] = [20, 24, 28]

print(aList)

a) [4, 20, 24, 8, 12, 16]

b) [4, 20, 24, 28]

c) [4, 20, 24, 28, 8, 12, 16]

d) [4,4,12,16]

17. Select all the correct options to join two lists in Python

listOne = ['a', 'b', 'c', 'd']

listTwo = ['e', 'f', 'g']

e) newList = listOne + listTwo

f) newList = extend(listOne, listTwo)

g) newList = listOne.extends(listTwo)

h) newList.extend(listOne, listTwo)

18. n = 1

for i in range(1, 11, 2):

product = n * i
print(product)
b. 1
3
5
7
9
b. 2
6
4
8
10
c. 2
4
6
8
10
d. Infinite loop

19. What will be the output of the following Python code?


i=2
while True:
if i%4 == 0:
break
print(i)
i += 1
a)1 2 3
b) error
c) 2 3
d) none of the mentioned

20. A new element is added to the list using the command?


a) list1.addEnd(1)
b) list1.addLast(1)
c) list1.append(1)
d) list1.add(1)

Q1 Problem Statement
Tina went to a fruit market to buy some fruits. She filled her fruit basket with different types
of fruits all together. But the vendor now asked Tina to separate each type of fruit and count
them, so that he can make the bill. Each type of fruit has a particular number written on it. Tina
finds it difficult to do so. Help her to count the number of fruits of each type.

You have given a list A of size N, which stores the number written on each fruit in the basket.
Your task it to count the number of fruits of each type.

Input Format:
The first line contains an integer N denoting the total number of fruits in the basket
The next N line contains N integers in sorted order representing the fruit number on each type of fruit.

Output Fomrat:
For each fruit type, print in a new line, print the number written on the fruit and the count of that fruit
in the basket separated by space.

CONSTRAINTS:
1<=N<=100
1<=A[i]<=100

Sample Input:
7 #N: Number of fruits
#list of N numbers in sorted order denoting the fruit type
1
1
1
2
3
3
4
Sample Output:
13 #here 1 is the number written on fruit, and the count of fruit is 3
21 #here 2 is the number written on fruit, and the count of fruit is 1
32
41

Rohan and Ajay are playing a game. The game says, they have been given a list of numbers and they
have to find out a pair in the list having maximum sum. Ajay is confused and is not able to find the
required pair, help him to find the solution.

You have given a list A containing N elements. Your task is to find the pair of numbers in the list

having maximum sum.

Write a python program which takes the size N and the list A as input and print the maximum sum

pair separated by space as the output.

INPUT FORMAT:

The first line contains an integer N denoting the total number of elements in the list

The next N line contains N integers representing the elements in of the list

OUTPUT FORMAT:

Print in a single line, the pair of elements from the list having the maximum sum

CONSTRAINTS:

1<N<=100

1<=A[i]<=100

EXAMPLE:

INPUT:

5 #N: number of elements

6 #N elements

3
2

OUTPUT:

65

Rohan and Ajay are playing a game. The game says, they have been given a list of numbers and they
have to find out a pair in the list having maximum sum. Ajay is confused and is not able to find the
required pair, help him to find the solution.

You have given a list A containing N elements. Your task is to find the pair of numbers in the list

having maximum sum.

Write a python program which takes the size N and the list A as input and print the maximum sum

pair separated by space as the output.

INPUT FORMAT:

The first line contains an integer N denoting the total number of elements in the list

The next N line contains N integers representing the elements in of the list

OUTPUT FORMAT:

Print in a single line, the pair of elements from the list having the maximum sum

CONSTRAINTS:

1<N<=100

1<=A[i]<=100

EXAMPLE:

INPUT:

5 #N: number of elements

6 #N elements

OUTPUT:
65

Q1. Whats the output of following code:


l=[[1,2,3],[4,5],6]
print (l[1:])

e) [[4, 5], 6]
f) [[2,3], [4,5],6]
g) [[4,5]]
h) [[1,2],[4,5]]

Q2. What is the output of the following code:

l = [["a","b","c"],["d","e","f"],["g","h","i"]]
print (l[1:][1])

e) ['g', 'h', 'i']


f) Syntax error
g) [["a","b","c"]]
h) [['g', 'h', 'i']]

Q3. What is the output of the following code:

list = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
print([t[:-1] + (500,) for t in list])
e) [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
f) [(10, 40, 20), (40, 50, 60), (70, 90, 80)]
g) [(10, 500, 20), (40, 500, 500), (70, 500, 80)]
h) [(10, 20, 500), (40, 50, 500), (70, 80, 500)]

Q4. What is the output of the following code:


X = [[12,7],
[4 ,5],
[3 ,8]]

result = [[X[j][i] for j in range(len(X))] for i in range(len(X[0]))]


for r in result:
print(r)

a) [12, 4, 3] b) [7,5,8] c) Error d) [3,4,12]

[7, 5, 8] [12, 4, 3] [8,5,7]

Q5. list, tuple, and range are the ___ of Data Types.

A. Sequence Types
B. Binary Types
C. Boolean Types
D. None of the mentioned above

Q6 Given a code:
str1 = 'hello'
newtext = str1[1:] + str1[0]
print('New string:', newtext)
What would newtext return?
e) oellh
f) llohe
g) lohel
h) elloh

Q7 What will be the output of this statement?

d = {"Meera":40, "Ram":45}
"Ram" in d

e. True
f. False
g. Error
h. None

Q8 Suppose d = {“Cally”:40, “New”:45}, to delete the entry for “new” what command do we use?

a) d.delete(“new”:45)
b) d.delete(“new”)
c) del d[“new”]
d) del d(“new”:40)

21. What will be the output of the following Python code snippet?

k = [print(i) for i in my_string if i not in "aeiou"]

a) prints all the vowels in my_string


b) prints all the consonants in my_string
c) prints all characters of my_string that aren’t vowels
d) prints only on executing print(k)

22. What will be the output of the following Python code?

a) [1, 3, 7]
b) [1, 2, 3]
c) [4, 3, 6]
d) [3, 3, 7]

3. Consider a dictionary

d = {"cally":40, "new":45}

To delete the entry for "new" what command do we use?


a) d.delete(“new”:45)
b) d.delete(“new”)
c) del d[“new”]
d) del d(“new”:40)
23. What will be the output of the following:

print(“Chitkara” +1+2+3)
a) Chitkara123
b) Chitkara
c) Error
d) Chitkara6

24. What type of data is: a=[(1,1),(2,4),(3,9)]?


a) Array of tuples
b) List of tuples
c) Tuples of lists
d) Invalid type

25. What will be the output of the following Python code?

a) {2,4,6}
b) Error, set comprehensions aren’t allowed
c) {8, 2, 10, 4, 6}
d) {8,10}

26. What will be the output?

A. ['I', 'am', 'fine']


B. ('I', 'am', 'fine')
C. “Iamfine”
D. ‘I am fine’
27. What is the output?
def tuple_indexing(tup):
tup[1] = 800
return tup

aTuple = (100, 200, 300, 400, 500)


print(tuple_indexing(aTuple))
A. (100, 200, 800, 300, 400, 500).
B. (100, 800, 200, 300, 400, 500)
C. (800, 100, 200, 300, 400, 500)
D. Nothing, it will cause an error.

9. Select the Python-related option that is right.


A. Both tuples and lists are mutable.
B. Both tuples and lists are immutable.
C. Tuples are immutable while lists are mutable.
D. Tuples are mutable while lists are immutable.
10. What is the output of the following code:
X = [[12,7],[4 ,5],[3 ,8]]

result = [[X[j][i] for j in range(len(X))] for i in range(len(X[0]))]


for r in result:
print(r)

a. [12, 4, 3] b) [7,5,8] c) Error d) [3,4,12]


[7, 5, 8] [12, 4, 3] [8,5,7]

SECTION-B (10*1 mark=10 marks)

Kirti has been asked to give a sentence in the form of a string as a function parameter. The task
is to print the sentence such that each word in the sentence is reversed.

Input Format:

The only line of input contains a string that represents the sentence given by Kirti.

Output Format:

The only line of output prints the sentence such that each word in the sentence is reversed.

Constraints:

0 <= N <= 100

Where N is the length of the input string.

Sample Input 1:

Welcome To Chitkara
Sample Output 1:

emocleW oT araktihC

Solution:

def rev_sentence(sentence):
words = sentence.split(" ")
new_words = [word[::-1] for word in words]
new_sentence = " ".join(new_words)
return new_sentence
sentence = input()
print(rev_sentence(sentence))

TestCase1 Hello World! olleH !dlroW

TestCase2 Jai Hind iaJ dniH

TestCase3 Well Done lleW enoD

TestCase4 Super Star repuS ratS

TestCase5 Day Night yaD thgiN

SECTION-C (10*1 mark=10 marks)

Ms. Gabriel Williams is a botany professor at District College. One day, she asked her
student Mickey to compute the average of all the plants with distinct heights in her
greenhouse.

Formula used:

Average = Sum of Distinct Heights / Total Number of Distinct Heights

Input Format

The first line contains the integer, N, the total number of plants.

The second line contains the N space separated heights of the plants.
Constraints

0 < N <= 100

Output Format

Output the average height value on a single line.

Sample Input

10

161 182 161 154 176 170 167 171 170 174

Sample Output

169

Solution:

def average(array):
sum_array = sum(set(array))
len_array = len(set(array))
output = int(sum_array/len_array)
return output;

n = int(input())
arr = list(map(int, input().split()))
result = average(arr)
print(result)

TestCase1 4 11

11 12 11 12

TestCase2 5 3
1 2 3 4 5

TestCase3 6 13
12 13 12 14 10 20

TestCase4 3 10
10 10 10

TestCase5 9 3
112314673
Q1. Which function is used to count the number of rows in a 2d-list?

A. count()
B. len()
C. index()
D. find()

Q2. Let setA={4,5,9}, setB={1,4,5}. What will be the result of the following snippet?
print(setA|setB)
28. {4,5,9,1,4,5}
29. {4,5}
30. {1}
31. {1,4,5,9}

Q3. Which of the following set operation includes all the elements that are in two sets but not
the one that are common to two sets?
A. Symmetric difference
B. Systematic difference
C. Common difference
D. Asymmetric difference
Q4. What will be the output of below Python code?
tuple1=(5,1,7,6,2)
tuple1.pop(2)
print(tuple1)
A. (5,1,6,2)
B. (5,1,7,6)
C. (5,1,7,6,2)
D. Error

Q5. What will be the output of above Python code?

d1={"abc":5,"def":6,"ghi":7}
print(d1[0])

A. abc
B. 5
C. {"abc":5}
D. Error

Q6. What will be the following Python code?


dict1={"a":10,"b":2,"c":3}
str1=""
for i in dict1:
str1=str1+str(dict1[i])+" "
str2=str1[:-1]
print(str2[::-1])

A. 3, 2
B. 3, 2, 10
C. 3 2 01
D. Error

Q7. What is the output of the following code:


l = [["a","b","c"],["d","e","f"],["g","h","i"]]
print (l[1:][1])

a. ['g', 'h', 'i']


b. Syntax error
c. [["a","b","c"]]
d. [['g', 'h', 'i']]

Q8. What is the output of the following code:

list = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
print([t[:-1] + (500,) for t in list])
a. [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
b. [(10, 40, 20), (40, 50, 60), (70, 90, 80)]
c. [(10, 500, 20), (40, 500, 500), (70, 500, 80)]
d. [(10, 20, 500), (40, 50, 500), (70, 80, 500)]
Q9. What is the output of the following code:

str1 = 'hello'
newtext = str1[1:] + str1[0]
print(newtext)
a. oellh
b. llohe
c. lohel
d. elloh

Q10. What is the output of following code:

names = {'Jan': 5, 'Emi': 3, 'Johny': 7, 'Enaleanor': 2}


list_o_names = []
for name in names:
if names[name] > 5:
list_o_names.append(name)
print(list_o_names)
a) ['Jan', 'Johny']
b) ['Jan', 'Emi', 'Enaleanor']
c) ['Johny']
d) ['Jan', 'Emi', 'Johny', 'Enaleanor']

SECTION-B (10*1 mark=10 marks)

Raman received a mail from his friend Ravi, for filling the slam book. While filling the
answer to a particular question, he inserted special characters at a particular index of every
word he entered. Now he wants his friend to retrieve that character from each word and
concatenate them in order to know the answer to his question. Write a program to help Ravi
in finding out the answer to that question.
Input Format:
First Line : Enter the String # Input the String
Second Line: Index Value # If index value is 2 then it is used to extract 3rd character
from each word
Output Format:
String concatenation of characters at given index value of each word
Sample Input:
keep exploring
2
Sample Output:
ep
Solution:
sample_str=str(input())
#print(sample_str)
K =int(input())
# Getting Kth element of each word
tmp = []
for sub in sample_str.split():
tmp.append(sub[K])
result = ''.join(tmp)
# printing result
print(str(result))
Test case keep exploring The K joined String is :
1 The original string is : keep exploring ep
enter value of index : 2

Test case keep exploring new things The K joined String is :


2 The original string is : keep exploring new things exeh
enter value of index : 1

Test case "keep exploring every opportunity" The K joined String is :


3 The original string is : "keep exploring every epep
opportunity"
enter value of index : 2

Test case Welcometo computer engineering The K joined String is :


4 The original string is : Welcometo computer cpi
engineering
enter value of index : 3

Test case basic python proggramming **** The K joined String is :


5 The original string is : basic python proggramming ihg*
****
enter value of index : 3

SECTION-C (10*1 mark=10 marks)

Problem Statement
Task: Ramesh and Rajkumar have M and N sets of Indian currency notes respectively. They
have decided to donate all those currency notes that are not common to M and N to the social
welfare society. After receiving them, the society arranged these currency notes in sorted
order and also display the total amount they received
Input Format
The first line contains N space-separated integers.
The second line contains M space-separated integers.
Output Format
The non-common elements are printed in an ascending order separated by one space and also
print the amount of all currency notes as last elements in the same line as received by the
social welfare society

Sample Input
1 2 5 10 # set of M currency notes
5 10 100 200 # set of N unique currency notes

Sample Output

1 2 100 200 303 # set of noncommon currency notes and the last element (303) is
the #sum of all (1+2+100+200=303) received by social welfare
Sample Test Cases
Case1 Input Output
1 1 2 1 2 5 10 18
5 10
2 2 5 10 100 5 10 200 500 715
2 100 200 500
3 5 10 100 1000 1 2 5 10 100 500 1000 2000 3618
1 2 500 2000
4 1 2 5 10 0
1 2 5 10
5 1 2 5 10 1 100 101
2 5 10 100

Solution
------------------
N=input().split()
Nint= [int(j) for j in N]
M=input().split()
Mint= [int(j) for j in M]
Nint=set(Nint)
Mint=set(Mint)
res=Nint.symmetric_difference(Mint)
res=list(res)
for k in sorted(res):
print(k, end=' ')
print(sum(res))

1. What will be the output of the following Python code?

l=[[2, 4, 6], [7, 6, 2]]


for i in range(len(l)):
for j in range(len(l[i])):
l[i][j]+=20
print(l)

a) No output
b) Error
c) [[2, 4, 6], [7, 6, 2]]
d) [[22, 24, 26], [27, 26, 22]]

2. Write a list comprehension to produce the list: [1, 2, 4, 8, 16……212].


a) [(2**x) for x in range(0, 13)]
b) [(x**2) for x in range(1, 13)]
c) [(2**x) for x in range(1, 13)]
d) [(x**2) for x in range(0, 13)]

3. What will the below Python code return?

list1= [0,2,5,1]
str1="8"
for i in list1:
str1=str1+i
print(str1)

a) 8025
b) 8
c) 15
d) Error

4. Which of the following will give "Mohan" as output?


If str1="John, Mohan, Aryan"

a) print(str1[-7:-12])
b) print(str1[-11:-7])
c) print(str1[-12:-6])
d) print(str1[-7:-11])

5. What will be the output for the following python code?

a={1:"A",2:"B",3:"C"}
for i,j in a.items():
print(i,j,end=" ")

a) 1 2 3
b) A B C
c) 1 A 2 B 3 C
d) 1:”A” 2:”B” 3:”C”

6. Which command will be used to correctly adds an item to the fruit dictionary with a key of
‘grapes’ and a value of 10?
fruits = {'apples': 1, 'bananas': 4, 'pears': 17, 'oranges': 14}
a) fruits['grapes']
b) fruits[‘grapes’]=10
c) insert ‘grapes’ in fruits
d) fruits[10]= ‘grapes’

7. There are two sets, s1 and s2, and which function will be used to check if all the elements of
s1 are present in s2 or not.
a) s2.issubset(s1)
b) s2.issuperset(s1)
c) s1.issuperset(s2)
d) s1.isset(s2)

8. Write the output of the following code:


set1={1,2,3}
set1.add(5)
set1.add(5)
print(set1)

a) {1,2,3,5}
b) {1,2,3}
c) {1,2,3,5,5}
d) It will throw an error as same element is added twice

9. What is the output of the following code?

text = "fun with python"


print(text.find("th",7,14))
a. 14
b. 7
c. TRUE
d. 11

10.
matrix = [[1, 2, 3, 4],
[4, 5, 6, 7],
[8, 9, 10, 11],
[12, 13, 14, 15]]

for i in range(0, 3):


print(matrix[i][3], end = " ")

a. 1 2 3
b. 4 5 6
c. 3 6 10
d. 4 7 11

Correct Answer : d

SECTION-B (10*1 mark=10 marks)

Q1 Problem Statement
There was a boy who was given an integer n, he created a two-dimensional array of
size (n×n) and later populated it in the following way, keeping in view that each character
should have white spaces between them:

• The matrix that the boy has created has positions on the minor diagonal (from the upper
right to the lower left corner) which receives 1 .
• The matrix that the boy has created has positions above this diagonal should recieve 0 .
• The matrix that the boy has created should have positions that is below the diagonal
should receive 2 .

The boy has to print the elements of the resulting array.

Input Format:
Enter the integer value: n (integer value)

Output Fomrat:
n*n Matrix

Sample INput:
4
Sample Output:
0001
0012
0122
1222

Input 1:
1

Output 1:
1

Input 2:
2

Output 2:
01
12

Input 3:
3

Output 3:
001
012
122

Input 4:
5

Output 4:
00001
00012
00122
01222
12222

Input 5:
8

Output 5:
00000001
00000012
00000122
00001222
00012222
00122222
01222222
12222222

Suitable Solution:

Solution 1:
def display(mat):
for i in range(n):
for j in range(n):
if (i + j==(n-1)):
a[i][j] = 1
elif (i + j<(n-1)):
a[i][j] = 0
else:
a[i][j] = 2
for row in a:
print(' '.join([str(elem) for elem in row]))

n = int(input())
a = [[0] * n for i in range(n)]
display(a)
SECTION-C (10*1 mark=10 marks)

Q1 Problem Statement
Input a list from the user that contains car brand names. The task is to find the length
of each brand name and print it. Also print the concatenated output of brands with the
maximum length.

Input Format:
Enter the number of brands: n (integer value)

Output Format:
Concatenated string with maximum number of characters

Sample input
3
Volvo
Bentley
Porsche
Sample output:
5
7
7
Bentley Porsche

Input 1:
3
Polonez
Audi
Porsche

Output:
7
4
7
Polonez Porsche

Input 2:
3
Charmant
Jeep
Chrysler

Output:
8
4
8
Charmant Chrysler

Input 3:
3
Toyota
Tesla
Trofeo

Output:
6
5
6
Toyota Trofeo

Input 4:
2
Tata
Ferrari

Output:
4
7
Ferrari

Input 5:
2
Mercedes
Maverick

Output:
8
8
Mercedes Maverick

Input 6:
3
Maruti
Hyundai
Honda

Output:
6
7
5
Hyundai

Suitable Solution:

Test Stub:

num = int(input())

l1_list = []

for r in range(num):

a = input()

l1_list.append(a)

# Write your code here

Solution:

num = int(input())

l1_list = []

for r in range(num):

a = input()

l1_list.append(a)

res=[]

x=[]

for i in l1_list:
x.append(len(i))

for i in x:

print(i)

ma=max(x)

for i in l1_list:

if ma == len(i):

res.append(i)

res=' '.join(res)

print(str(res))

32. What will be the output of the following Python code?


my_tuple = (1,2,3,4)
print len(my_tuple)

a) 1
b) 0
c) 4
d) Error

33. What will be the output of the following Python code?


a={5,10,15,20,25}
a.add(15)
print(a)

a) {5,10,15,15,20,25}
b) {5,10,15,20,25}
c) Error as there is no add function for set data type
d) Error as 15 already exists in the set

34. What will be the output of the following Python code?

tuple= ('a','b','c','d','e','f','g')
print(tuple[0:5])
print(tuple[-1:-5:-2])
a) (‘a’, ‘b', 'c', 'd', 'e')
(‘g’,‘e’)
b) (‘a’, ‘b', 'c', 'd', 'e',)
(‘g’, ‘e’,)
c) (‘a’, ‘b', 'c', 'd')
(‘g’, ‘e’)
d) (‘a’, ‘b', 'c', 'd',)
(‘g’, ‘e’,)

35. What will be the list comprehension to produce the following list :

[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]

a) [(2**x) for x in range(0, 13)]


b) [(x**2) for x in range(1, 13)]
c) [(2**x) for x in range(1, 13)]
d) [(x**2) for x in range(0, 13)]

36. What will be the output of following Python code?

k = {"Backward":40, "Forward":45}
print(list(k.keys( )))

a) [Backward, Forward]
b) (‘Backward’, ‘Forward’)
c) ("Backward":40, "Forward":45)
d) [‘Backward’, ‘Forward’]

37. What will be the output of following Python code?

string = "Hello Program"


print(string[:5] + "Python")

a) Hello Python
b) Hello Program
c) HelloPython
d) Error

38. What will be the output of following Python code?

x = [i**+1 for i in range(3)]; print(x);

a) [0, 1, 2]
b) [1, 2, 5]
c) error,**+ is an invalid operator
d) error, ‘;’is not allowed

39. Keys of dictionary must be:

A:Unique
B: Antique
C: Mutable
D: Integers

40. x = {4, 5, (6, 7)}

An operation is done on x and afterthat print(x) gives the below output:

x = {4, 5, (6, 7), 10, 11}

What operation is done? Please select the correct option

A: x.append(10, 11)
B: x.update([10, 11])
C: x.add((10, 11))
D: x.add(10, 11)

41. list = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
print([t[:-1] + (500,) for t in list])

e. [(10, 20, 40), (40, 50, 60), (70, 80, 90)]


f. [(10, 40, 20), (40, 50, 60), (70, 90, 80)]
g. [(10, 500, 20), (40, 500, 500), (70, 500, 80)]
h. [(10, 20, 500), (40, 50, 500), (70, 80, 500)]

SECTION-B (10*1 mark=10 marks)

Problem Statement
Write a program to do basic string compression. For a character which is
consecutively repeated more than once, replace consecutive duplicate occurrences
with the count of repetitions

Example:
If a string has 'x' repeated 5 times, replace this "xxxxx" with "x5".

The string is compressed only when the repeated character count is more than 1.

Note:
You are not required to print anything. It has already been taken care of. Just
implement the given function.

Input Format:
The first and only line of input contains a string without any leading and trailin g
spaces.
Output Fomrat:
The output contains the string after compression printed in single line.

Constraints :
0 <= N <= 10^6

Where 'N' is the length of the input string.

Time Limit: 1 sec

Input 1:
aaabbccdsa

Output 1:
a3b2c2dsa

Explanation for Sample Output 1:


In the given string 'a' is repeated 3 times, 'b' is repeated 2 times, 'c' is repeated 2
times and 'd', 's' and 'a' and occuring 1 time hence no compression for last 3
characters.

Solution:

def ab(a):
i=0
x=''
while(i<len(a)):
j=i+1
c=1
while j<len(a) and (a[i]==a[j]):
j+=1
c+=1
if c==1:
x+=a[i]
else:
x+=a[i]+str(c)
i=j
return x
a=input()
print(ab(a))

TestCase1 Raaakkkkeeeeeeeessssss Ra3k4e8s9h


sssh

TestCase2 aaabbcddeeeee a3b2cd2e5

TestCase3 reeeenuuu re4nu3

TestCase4 Chhhitkaaaraa Ch3itka3ra2

TestCase5 Heeelllo He3l3o

SECTION-C (10*1 mark=10 marks)

Q1. Samita is assigned a task by her class teacher to convert a list into 2-d list. Help Samita to
complete her task. The task detail is given below:

Given a list, the task is to split the list at every Nth element and create a 2-d list.

Sample Input format:

n-→nth element for splitting

list-→ single line input list of any length

Output format:

2d list

Sample Input

4567891234566

Sample Output:
[['4', '8', '3', '6'], ['5', '9', '4'], ['6', '1', '5'], ['7', '2', '6']]

SOLUTION:

n=int(input())

C = [item for item in input().split()]

def list_slice(S, step):

return [S[i::step] for i in range(step)]

print(list_slice(C,n))

Testcases

Test Case1 Input


3
1 2 3 45 6 2 3 7
Output
[['1', '45', '3'], ['2', '6', '7']
, ['3', '2']]
Test Case2 Input
2
12345
Output
[[‘1’, ‘3’, ‘5’], [‘2’, ‘4’]]

Test Case3 Input


1

12345

Output
[['1', '2', '3', '4', '5']]
Test Case 4 Input

12345

Output:

[['1', '5'], ['2'], ['3'], ['4']]


Test Case 5 Input

12345

Output

[['1'], ['2'], ['3'], ['4'], ['5']


]
SOLUTION:

n=int(input())
C = [item for item in input().split()]
def list_slice(S, step):
return [S[i::step] for i in range(step)]
print(list_slice(C,n))

42. What will be the output of the following Python code?

i=0
while i < 6:
print(i)
i += 1
else:
print(1)
a) 0 1 2 3 4 5 1
b) 0 1 2 1 0
c) 0 1 2 1
d) error

43. What will be the output of the following Python code?

x = " pqrcef"
while i in a:
print(i, end=" ")
a) p q r c e f
b) pqrcef
c) Error
d) i i i i i i …

44. What will be the output of the following Python code?

def Person(message, times = 1):


print(message * times)
Person('Aman')
Person('Niya', 5)
a) Aman
Niya, Niya, Niya, Niya, Niya
b) Aman
Niya 5
c) Aman
Niya, Niya, Niya, Niya, Niya
d) Aman
NiyaNiyaNiyaNiyaNiya

45. Which one of the following is a valid Python if statement:


i) if a>=2 :
j) if (a >= 2)
k) if (a => 22)
l) if a >= 22

46. What is the output of the following list operation

aList = [10, 20, 30, 40, 50, 60, 70, 80]

print(aList[2:5])

print(aList[:4])

print(aList[3:])

i) [20, 30, 40, 50]

[10, 20, 30, 40]

[30, 40, 50, 60, 70, 80]

j) [30, 40, 50]

[10, 20, 30, 40]

[40, 50, 60, 70, 80]

k) [20,30,40,50]

[10,20,30,40]

[40,50,60,70]

l) None of these
47. What is the output of the following list assignment

aList = [4, 8, 12, 16]

aList[1:4] = [20, 24, 28]

print(aList)

a) [4, 20, 24, 8, 12, 16]

b) [4, 20, 24, 28]

c) [4, 20, 24, 28, 8, 12, 16]

d) [4,4,12,16]

48. Select all the correct options to join two lists in Python

listOne = ['a', 'b', 'c', 'd']

listTwo = ['e', 'f', 'g']

i) newList = listOne + listTwo

j) newList = extend(listOne, listTwo)

k) newList = listOne.extends(listTwo)

l) newList.extend(listOne, listTwo)

49. n = 1

for i in range(1, 11, 2):

product = n * i
print(product)
c. 1
3
5
7
9
b. 2
6
4
8
10
c. 2
4
6
8
10
d. Infinite loop

50. What will be the output of the following Python code?


i=2
while True:
if i%4 == 0:
break
print(i)
i += 1
a)1 2 3
b) error
c) 2 3
d) none of the mentioned

51. A new element is added to the list using the command?


a) list1.addEnd(1)
b) list1.addLast(1)
c) list1.append(1)
d) list1.add(1)

SECTION-B(Coding Question) (1x10 marks=10 marks)

Rohan and Ajay are playing a game. The game says, they have been given a list of numbers and they
have to find out a pair in the list having maximum sum. Ajay is confused and is not able to find the
required pair, help him to find the solution.

You have given a list A containing N elements. Your task is to find the pair of numbers in the list

having maximum sum.

Write a python program which takes the size N and the list A as input and print the maximum sum

pair separated by space as the output.

INPUT FORMAT:

The first line contains an integer N denoting the total number of elements in the list

The next N line contains N integers representing the elements in of the list
OUTPUT FORMAT:

Print in a single line, the pair of elements from the list having the maximum sum

CONSTRAINTS:

1<N<=100

1<=A[i]<=100

EXAMPLE:

INPUT:

5 #N: number of elements

6 #N elements

OUTPUT:

65

SOLUTION:

n=int(input())

li=[]

ele1 = 0

ele2 = 0

for i in range(0, n):

ele = int(input())

li.append(ele)

maxSum=0

Sum=0

for i in range(0, n-1):

for j in range(i+1,n):
Sum=li[i]+li[j]

if(Sum>maxSum):

maxSum=Sum

ele1=li[i]

ele2=li[j]

print(ele1,ele2)

Test Case1:
2
34
23
34 23

Test Case2:
3
5
5
4
55

Test Case3:
7
3
5
2
7
1
0
5
57

Test Case4:
6
21
12
31
13
41
14
31 41
Test Case5:
4
50
25
12
6
50 25
In [ ]:

Q1: What is the output of the following Python code snippet?


for n in range (-2,-5,-1):
print (n, end = “,”)
a) -2, -1, -3, -4
b) -2, -1, 0, 1, 2, 3,
c) -2, -1, 0
d) -2, -3, -4,

Q2: What will be the output of the following code snippet?


j=1
while True:
if j%7 == 0:
break
print(j)
j += 1
a) 1 2 3 4 5 6
b) 1 2 3 4 5 6 7
c) Error
d) none of the mentioned

Q3: What is the output of the given below program?


a = d = true
if (a and d):
print("Hi")
else:
print("Hello")
a) Hello
b) Hi
c) Compiled Successfully, No Output.
d) Error

Q4: What will be the output of the following Python code snippet?
x=5
def func(x):
print('x is', x)
x = 20
print('Changed local x to', x)
func(x)
print('x is now', x)
a) x is 5
Changed local x to 20
x is now 5
b) x is 5
Changed local x to 20
x is now 20
c) x is 5
Changed local x to 20
x is now 100
d) None of the mentioned
Q5: What will be the output of the following code snippet?
def solv(a, b):
return b if a == 0 else solv(b % a, a)
print(solv(20, 50))
a) 10
b) 20
c) 50
d) 1

Q6: Suppose list is [8, 33, 22, 14, 225], What is list[-1]?
a) Error
b) None
c) 225
d) 2

Q7: What will be the output of the following Python code?

def Person(message, times = 1):


print(message * times)
Person('Aman')
Person('Niya', 5)
a) Aman
Niya, Niya, Niya, Niya, Niya
b) Aman
Niya 5
c) Aman
Niya, Niya, Niya, Niya, Niya
d) Aman
NiyaNiyaNiyaNiyaNiya

Q8: Which command is used to insert 6 to the third position in list?


a) list.insert(3, 6)
b) list.insert(2, 6)
c) list.add(3, 6)
d) list.append(3, 6)

Q 9. Which of the following loops correctly computes 1/2 + 2/3 + 3/4 + ... + 99/100?

A:
sum = 0
for j in range(1, 99):
sum += j / (j + 1)

print("Sum is", sum)

B:
sum = 0
for j in range(1, 100):
sum += j / (j + 1)

print("Sum is", sum)

C:
sum = 0
for i in range(1.0, 99.0):
sum += j / (j + 1)

print("Sum is", sum)

D:
sum = 0
for i in range(1.0, 100.0):
sum += j / (j + 1)
a) BCD
b) B
c) ABCD
d) BD

Q10. What would be the output:

thisList = ["square", "circle", "triangle", "octagon"]

if "tryangle" in thisList:
print("Yes, 'triangle' is in the list")
else:
print("No triangle here!")
a) Yes, 'triangle' is in the list
b) No triangle here!
c) Error
d) No tryangle here!

SECTION-B (1*10 mark=10 marks)


(All questions are compulsory)

Q1 Problem Statement
Problem Statement:
You are in-charge of the cake for your niece's birthday and have decided the cake will have
one candle for each year of her total age. When she blows out the candles, she’ll only be able
to blow out the tallest ones.
For example, if your niece is turning 5 years old, and the cake will have candles of height
4,2,4,3,4 she will be able to blow out 3 candles successfully, since the tallest candle is of height
4 and there are 3 such candles.

Given the height of each individual candle, find and print the number of candles she can
successfully blow out.

Input Format
The first line contains a single integer, n ,denoting the number of candles on the cake.
The second line contains n line-separated integers, where each integer describes the height of
candle i.

Output Format
Print the number of candles the can be blown out on a new line.

For Example:
Sample Input
5
4
2
4
3
4
Sample Output
3
Explanation:
We have one candle of height 2 , one candle of height 3, and rest of the three candles of height
4 . Your niece only blows out the tallest candles, meaning the candles where height=4 . Because
there are 3 such candles, we print 3 on a new line as output.

Test Case Sample Input Sample Output


1 5 3

2 4 2
3

3 3 3

4 6 2

5 7 4

6
Solution:
n=int(input()) #Taking the input from user about total number of candles.
l=[] #Creating Empty list
k=0 #Variable to hold the largest value
l=[]
for i in range(0,n):
l.append(int(input()))

for i in range(len(l)): #Iteration for finding the largest height candle


if(l[i]>k):
k=l[i]
c=0 #variable to count the total number of appearances of largest value of the list
for j in range(len(l)): #iteration to count the total appearances of largest height candle
if l[j]==k:
c=c+1
print(c) #printing output

52. What will be the output of the following Python code?

i=0
while i < 6:
print(i)
i += 1
else:
print(1)
a) 0 1 2 3 4 5 1
b) 0 1 2 1 0
c) 0 1 2 1
d) error

53. What will be the output of the following Python code?

x = " pqrcef"
while i in a:
print(i, end=" ")
a) p q r c e f
b) pqrcef
c) Error
d) i i i i i i …
54. What will be the output of the following Python code?

def Person(message, times = 1):


print(message * times)
Person('Aman')
Person('Niya', 5)
a) Aman
Niya, Niya, Niya, Niya, Niya
b) Aman
Niya 5
c) Aman
Niya, Niya, Niya, Niya, Niya
d) Aman
NiyaNiyaNiyaNiyaNiya

55. Which one of the following is a valid Python if statement:


m) if a>=2 :
n) if (a >= 2)
o) if (a => 22)
p) if a >= 22

56. What is the output of the following list operation

aList = [10, 20, 30, 40, 50, 60, 70, 80]

print(aList[2:5])

print(aList[:4])

print(aList[3:])

m) [20, 30, 40, 50]

[10, 20, 30, 40]

[30, 40, 50, 60, 70, 80]

n) [30, 40, 50]

[10, 20, 30, 40]

[40, 50, 60, 70, 80]

o) [20,30,40,50]
[10,20,30,40]

[40,50,60,70]

p) None of these

57. What is the output of the following list assignment

aList = [4, 8, 12, 16]

aList[1:4] = [20, 24, 28]

print(aList)

a) [4, 20, 24, 8, 12, 16]

b) [4, 20, 24, 28]

c) [4, 20, 24, 28, 8, 12, 16]

d) [4,4,12,16]

58. Select all the correct options to join two lists in Python

listOne = ['a', 'b', 'c', 'd']

listTwo = ['e', 'f', 'g']

m) newList = listOne + listTwo

n) newList = extend(listOne, listTwo)

o) newList = listOne.extends(listTwo)

p) newList.extend(listOne, listTwo)

59. n = 1

for i in range(1, 11, 2):

product = n * i
print(product)
d. 1
3
5
7
9
b. 2
6
4
8
10
c. 2
4
6
8
10
d. Infinite loop

60. What will be the output of the following Python code?


i=2
while True:
if i%4 == 0:
break
print(i)
i += 1
a)1 2 3
b) error
c) 2 3
d) none of the mentioned

61. A new element is added to the list using the command?


a) list1.addEnd(1)
b) list1.addLast(1)
c) list1.append(1)
d) list1.add(1)

SECTION-B(Coding Question) (1x10 marks=10 marks)

Rohan and Ajay are playing a game. The game says, they have been given a list of numbers and they
have to find out a pair in the list having maximum sum. Ajay is confused and is not able to find the
required pair, help him to find the solution.

You have given a list A containing N elements. Your task is to find the pair of numbers in the list

having maximum sum.

Write a python program which takes the size N and the list A as input and print the maximum sum

pair separated by space as the output.


INPUT FORMAT:

The first line contains an integer N denoting the total number of elements in the list

The next N line contains N integers representing the elements in of the list

OUTPUT FORMAT:

Print in a single line, the pair of elements from the list having the maximum sum

CONSTRAINTS:

1<N<=100

1<=A[i]<=100

EXAMPLE:

INPUT:

5 #N: number of elements

6 #N elements

OUTPUT:

65

SOLUTION:

n=int(input())

li=[]

ele1 = 0

ele2 = 0

for i in range(0, n):

ele = int(input())

li.append(ele)

maxSum=0
Sum=0

for i in range(0, n-1):

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

Sum=li[i]+li[j]

if(Sum>maxSum):

maxSum=Sum

ele1=li[i]

ele2=li[j]

print(ele1,ele2)

Test Case1:
2
34
23
34 23

Test Case2:
3
5
5
4
55

Test Case3:
7
3
5
2
7
1
0
5
57

Test Case4:
6
21
12
31
13
41
14
31 41
Test Case5:
4
50
25
12
6
50 25

In [ ]:

You might also like