S2Q2 · Count Digits in Text¶
⚡ Quick Reference
Type: Full I/O problem
Core idea: Read n lines, count every character that satisfies ch.isdigit().
n = int(input())
count = 0
for _ in range(n):
count += sum(1 for ch in input() if ch.isdigit())
print(count)
Key rules:
- Count digits 0-9 only, across all lines combined
- str.isdigit() is the cleanest check
- Print a single integer at the end
Problem Statement¶
Problem
Read n (the number of lines), then n lines of text. Print the total count of numeric digit characters (0-9) present across all lines.
Examples:
3
hello 123
world 45
no digits here
5
2
000
999
6
1
abc
0
Understanding the problem¶
Walk through the first example character by character:
| Line | Content | Digits found |
|---|---|---|
| 1 | hello 123 |
1, 2, 3 |
| 2 | world 45 |
4, 5 |
| 3 | no digits here |
(none) |
Total: 3 + 2 + 0 = 5
isdigit() vs checking '0' <= ch <= '9'
Both work for plain ASCII digits, but str.isdigit() is more readable and idiomatic. Note that str.isdigit() also returns True for some Unicode digit characters (like superscripts), but for OPPE inputs with standard ASCII text this makes no practical difference.
Solution approaches¶
Key takeaways¶
str.isdigit() for character classification
Python's string methods let you classify characters without manual range checks. ch.isdigit() is cleaner than '0' <= ch <= '9' and signals intent clearly.
Flattening nested iteration with a generator
sum(ch.isdigit() for line in text for ch in line) uses a nested generator expression to iterate all characters across all lines in one pass. bool values are treated as 0/1 by sum(), so no explicit if is needed.
Running total vs. collect-then-count
For large inputs, updating a running count inside the loop uses O(1) memory. The list comprehension approach stores all lines first -- both are fine for OPPE inputs, but the running total is worth knowing for general use.