A classic trick question: how many times does the digit 9 appear between 1 and 100? Most people answer 19. The correct answer is 20 — 9, 19, 29, ..., 99 give 10 in the ones place, and 90–99 give 10 in the tens place. The number 99 is counted twice.
I turned this into a small Python package, H9A.
Install and use
pip install h9a
h9a # 9 in 1..100 -> 20
h9a --digit 0 --start 0 --end 9
h9a --json # machine-readable output
h9a --screenshot # terminal-style PNG
Why it's fast
The first version iterated the range. A range of a billion numbers meant a billion iterations. I replaced it with a closed-form, per-place formula: for each decimal position, the count comes from division and modulo on the endpoints. Ranges up to 1,000,000,000,000 now resolve in microseconds.
Extras
-
richcolorized output,pyfigletASCII banner, Pillow screenshots - Library API:
count_digit()returns a per-placeDigitCount - 74 tests, ruff, mypy, pre-commit, CI docs + container publishing
- MIT-licensed, Python 3.8+
Source: https://github.com/rkriad585/h9a
Docs: https://rkriad585.github.io/h9a/
PyPI: https://pypi.org/project/h9a/

Top comments (0)