Test Index

CBSE Class 12 Computer Science 2026 Paper Set 4 Get it on Google PlayDownload on the App Store

© examsnet.com
Question : 25 of 37
Marks: +1, -0
What possible output(s) from the given options will NOT be displayed when the following code is executed ? Also, mention, for how many iterations the for loop in the given code will run ?
import random
a = [1,2,3,4,5,6]
for i in range(4):
j = random.randrange(i,5)
print(a[j],end='-')
print()
Options :
(A) 3-4-5-4-
(B) 2-2-4-5-
(C) 4-3-3-5-
(D) 5-1-2-4-
Solution:  
Concept:
random.randrange(i, 5) returns a random integer from i up to 4 (the stop value 5 is excluded). range(4) gives i = 0, 1, 2, 3, so the loop runs 4 times.
Possible values in each iteration (a = [1,2,3,4,5,6], index 0 to 5):
ij can bea[j] can be
00, 1, 2, 3, 41, 2, 3, 4, 5
11, 2, 3, 42, 3, 4, 5
22, 3, 43, 4, 5
33, 44, 5
Checking the options (1st, 2nd, 3rd, 4th printed value):
(A) 3, 4, 5, 4: all allowed, so it can be displayed.
(B) 2, 2, 4, 5: all allowed, so it can be displayed.
(C) 4, 3, 3, 5: all allowed, so it can be displayed.
(D) 5, 1, 2, 4: the 2nd value must be at least 2 (it is 1) and the 3rd at least 3 (it is 2), so it can never be displayed.
Answer:
Output that will NOT be displayed: (D) 5-1-2-4-
Number of iterations of the for loop: 4
© examsnet.com
Advertisements
Go to Question: