Write a program to count the number of capital letters in a file?
Assesses fundamental understanding of Python conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
Here is a memory-efficient Python program to count uppercase capital letters in a file:
def count_uppercase_letters(filepath: str) -> int:
"""Counts uppercase letters in a file line-by-line for memory efficiency."""
total_capitals = 0
with open(filepath, "r", encoding="utf-8") as file:
for line in file:
total_capitals += sum(1 for char in line if char.isupper())
return total_capitals
# Example execution
count = count_uppercase_letters("document.txt")
print(f"Total capital letters: {count}")
### Why Line-by-Line Iteration Matters:
Reading the entire file with .read() loads the full content into RAM simultaneously. Iterating line-by-line (for line in file) processes text in a memory-efficient stream, allowing the script to effortlessly process multi-gigabyte files without crashing.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.