S2Q1 · Count Odd 3-Digit Numbers (Ignore None)¶
⚡ Quick Reference
Function: count_odd_three_digit_nums(nums: list) -> int
Core idea: filter out None, then count elements that are three-digit (using abs) and odd.
def count_odd_three_digit_nums(nums):
return sum(
1 for n in nums
if n is not None
and 100 <= abs(n) <= 999
and n % 2 != 0
)
Key rules:
- Skip None values - check n is not None first
- Three-digit: 100 ≤ abs(n) ≤ 999 (ignores negative sign)
- Odd: n % 2 != 0
- All three conditions must hold
Problem Statement¶
Problem
Write a function count_odd_three_digit_nums(nums) that counts elements that are not None, are three-digit numbers (ignoring sign), and are odd.
Examples:
[101, -203, None, 99, 300]
2
[None, 120, 301, -401, 78]
2
[10, 305, 507, 99]
2
Tracing all examples¶
Example 1: [101, -203, None, 99, 300]
n |
Not None? | abs(n) |
3-digit? | Odd? | Count? |
|---|---|---|---|---|---|
| 101 | ✅ | 101 | ✅ | ✅ | ✅ |
| -203 | ✅ | 203 | ✅ | ✅ | ✅ |
| None | ❌ | - | - | - | ❌ |
| 99 | ✅ | 99 | ❌ (2 digits) | - | ❌ |
| 300 | ✅ | 300 | ✅ | ❌ (even) | ❌ |
Count = 2 ✓
Example 2: [None, 120, 301, -401, 78]
n |
Not None? | 3-digit? | Odd? | Count? |
|---|---|---|---|---|
| None | ❌ | - | - | ❌ |
| 120 | ✅ | ✅ | ❌ (even) | ❌ |
| 301 | ✅ | ✅ | ✅ | ✅ |
| -401 | ✅ | ✅ | ✅ | ✅ |
| 78 | ✅ | ❌ | - | ❌ |
Count = 2 ✓
Solution approaches¶
Key takeaways¶
Check None first with "is not None"
Always check n is not None before calling abs(n) or n % 2. Calling abs(None) raises a TypeError. Python's short-circuit and ensures the later conditions only run when n is not None.
abs() handles negative three-digit numbers
abs(-203) = 203 which is in range [100, 999]. Without abs(), negative numbers would always fail the range check since -203 < 100.
n % 2 != 0 for odd - use original n, not abs(n)
In Python, -203 % 2 == 1 (odd) and -204 % 2 == 0 (even), so the odd check works correctly on negative numbers directly. Using abs(n) % 2 would also work but is redundant.