easy +8 pts

Digit Expansion Generator

Build a generator that yields the decimal digits of any integer one by one.

Write a generator function named `digit_expansion(n)` that takes a non-negative integer `n` and yields its decimal digits one by one, from the most significant digit to the least significant digit. For example, `digit_expansion(1234)` should yield 1, then 2, then 3, then 4. If `n` is 0, the generator should yield exactly one digit: 0. You must not convert `n` to a string; instead, extract digits mathematically (e.g., using division and modulo). The result must be a generator object, so use `yield` in your implementation. The function signature is `def digit_expansion(n: int):`.

Constraints

0 <= n <= 10^9 (fits in a standard Python int). The generator should handle large inputs efficiently, using O(log10(n)) time and O(1) extra space.

Example

>>> list(digit_expansion(1234))
[1, 2, 3, 4]
>>> list(digit_expansion(0))
[0]
>>> list(digit_expansion(7))
[7]
>>> list(digit_expansion(9001))
[9, 0, 0, 1]
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

To get the most significant digit first, you can determine the number of digits using a while loop, then build from high to low.
Alternatively, you can collect digits from least significant to most significant and then reverse them, but that requires storing them; try to avoid that.
Use division and modulo only; do not use string conversion.
Remember to special-case 0 so that it yields exactly one zero.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.