Test Index

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

© examsnet.com
Question : 29 of 37
Marks: +1, -0
(a) Write a Python function that counts and returns the number of digits appearing in the text file "Space.txt". For example, if the file contains :
Space    exploration    has   unlocked    incredible
advancements in technology and science. Since the
first moon landing in 1969, space agencies have sent
probes to Mars, Jupiter and beyond. The ISS,
orbiting Earth at about 400 km, serves as a hub for
research. With missions planned for 2030, humanity’s
cosmic journey continues!
Then the function should return 11.
OR
(b) Write a Python function that displays the words in which the lowercase letter 'e' appears at least twice in the text file 'Space.txt'. For example, if the file contains :
Space    exploration    has   unlocked    incredible
advancements in technology and science. Since the
first moon landing in 1969, space agencies have sent
probes to Mars, Jupiter and beyond. The ISS,
orbiting Earth at about 400 km, serves as a hub for
research. With missions planned for 2030, humanity’s
cosmic journey continues!
Then the function should display :
incredible advancements science. agencies serves
research.
Solution:  
(a)
Concept: Open the file in read mode, read the whole text with read(), check every character with isdigit() and count the ones that are digits.
def CountDigits():
F = open("Space.txt", "r")
data = F.read()
F.close()
count = 0
for ch in data:
if ch.isdigit():
count += 1
return count
print(CountDigits())
Explanation:
The digits in the sample text are 1969 (4 digits), 400 (3 digits) and 2030 (4 digits), so the function returns 4 + 3 + 4 = 11. (ch in '0123456789' or '0' <= ch <= '9' can be used in place of isdigit().)
OR (b)
Concept: Read the text, split it into words with split() (which splits on any number of spaces and on line breaks) and print each word for which word.count('e') is 2 or more.
def ShowWords():
F = open("Space.txt", "r")
words = F.read().split()
F.close()
for word in words:
if word.count('e') >= 2:
print(word, end=' ')
ShowWords()
Output for the sample file:
incredible advancements science. agencies serves research.
Explanation:
incredible, advancements, science., agencies, serves and research. each contain two lowercase 'e'. Words such as Space, exploration, sent, have and probes contain only one, so they are not shown. The full stop stays attached to science. and research. because split() breaks only on white space.
© examsnet.com
Advertisements
Go to Question: