Test Index

CBSE Class 12 Computer Science 2025 Paper Compartment Get it on Google PlayDownload on the App Store

© examsnet.com
Question : 25 of 37
Marks: +1, -0
Identify the correct possible output(s) of the following code segment. Also write the minimum and the maximum possible values of the variable b.
import random
s="War and Peace"
a=len(s)//2
for i in range(4):
b=random.randrange(i,a)
print(s[b],end='+')
(A) n+P+d+a+
(B) W+r+n+n+
(C) e+r+W+a+
(D) a+P+e+r+
Solution:  
Concept: random.randrange(i, a) returns an integer from i up to a-1 (the stop value is excluded).
Working:
len("War and Peace") = 13, so a = 13//2 = 6.
Characters at indexes 0 to 5:
Index012345
s[index]War(space)an
ib = randrange(i, 6)possible s[b]
00 to 5W, a, r, space, a, n
11 to 5a, r, space, a, n
22 to 5r, space, a, n
33 to 5space, a, n
Checking the options:
(A) n+P+d+a+: 'P' (index 8) and 'd' (index 6) can never be printed. Not possible.
(B) W+r+n+n+: W (i=0, b=0), r (i=1, b=2), n (i=2, b=5), n (i=3, b=5). Possible.
(C) e+r+W+a+: 'e' is not in indexes 0 to 5, and 'W' (index 0) cannot come when i=2. Not possible.
(D) a+P+e+r+: 'P' and 'e' can never be printed. Not possible.
Result:
Correct possible output: (B) W+r+n+n+
Minimum possible value of b = 0 (when i = 0)
Maximum possible value of b = 5 (= a - 1)
© examsnet.com
Advertisements
Go to Question: