Practice Question 22
In this question, we will write a function that reads a file and identifies the shortest (smallest) word based on the number of characters it contains.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
To find the minimum value in a list, we follow this strategy:
-
Read and Split: Convert the file content into a list of words.
-
The Initial Assumption: We assume the first word in the list is the smallest.
-
The Comparison Loop: We compare every other word in the list with our “current smallest.”
-
The Update: If we find a word with a
len()smaller than our current smallest, we update our variable.
Let’s Code as per the above logic :
def displaySmallestWord():
f = open("text.txt", "r")
data = f.read()
wordlist = data.split()
if len(wordlist) > 0:
# Start by assuming the first word is the smallest
smallest = wordlist[0]
for word in wordlist:
# Compare length of current word with our smallest
if len(word) < len(smallest):
smallest = word
print("The smallest word in the file is:", smallest)
print("Length of the smallest word is:", len(smallest))
else:
print("The file is empty.")
f.close()
# To call the function:
displaySmallestWord()
Important Notes for Students
As a teacher, I want you to pay close attention to these points, as they are where most students make mistakes in exams:
-
Handling Empty Files: Always check
if len(wordlist) > 0. If you try to accesswordlist[0]on an empty file, your program will crash with anIndexError. -
Tie-Breaker: If there are two words of the same smallest length (like “is” and “to”), this logic will keep the first one it found. To get the last one, you would change
<to<=. -
Alternative (The
min()function): Python has a built-in shortcut:smallest = min(wordlist, key=len). While this is great for real-world coding, using aforloop (as shown above) is usually preferred in Board Exams to show you understand the underlying algorithm.
Teacher’s Secret Tip for Exams:
This exact same structure is used to find the Largest word. Just change smallest = wordlist[0] to largest = wordlist[0] and change the condition to if len(word) > len(largest):
Want to practice more? If you found this helpful, I have compiled a full list of 30 practice problems just like this one. Each question focuses on a different logic to help you become a pro at File Handling.
Click here to view the full 30-Question Practice Set
Exam Special Recommendation: If you are studying in 12th class and preparing for your board exam, then go for the “Computer Science with Python Sample Paper Book“. It contains 3 previous years’ papers and 7 practice papers solved strictly as per the CBSE pattern. Click here to purchase your copy!