Skip to content

Library API

H9A can be used as a Python library. The public API is exported from the h9a package (see h9a/__init__.py).

Installation

python -m pip install .

For screenshot generation, install the screenshot extra (adds Pillow):

python -m pip install .[screenshot]

count_digit()

Count how many times a digit appears in an inclusive range of numbers.

from h9a import count_digit

result = count_digit()                     # digit=9, start=1, end=100
result = count_digit(digit=7, start=1, end=999)

Signature:

count_digit(digit: int = 9, start: int = 1, end: int = 100) -> DigitCount

Raises ValueError if digit is not 0-9 or if start > end.

DigitCount

The frozen dataclass returned by count_digit():

Field Type Description
digit int The digit that was counted.
start int First number of the range.
end int Last number of the range.
by_position dict[int, int] Place value (1, 10, 100, ...) to count.
total int Sum of all per-place counts.
>>> result = count_digit()
>>> result.total
20
>>> result.by_position
{1: 10, 10: 10}

place_name()

Return the human-readable name of a decimal place value.

from h9a import place_name

place_name(1)     # 'ones'
place_name(10)    # 'tens'
place_name(100)   # 'hundreds'

build_lines()

Return the styled output as a list of (text, style) tuples. Style names are banner, subtitle, notice, step, explanation_title, explanation, result, and plain.

from h9a import build_lines, count_digit

for text, style in build_lines(count_digit()):
    print(f"[{style}] {text}")

render_text()

Return the plain-text (unstyled) output as a single string.

from h9a import render_text, count_digit

print(render_text(count_digit()))

generate_screenshot()

Render the output to a terminal-style PNG image. Requires Pillow.

from h9a import generate_screenshot

generate_screenshot("Screenshots/home.png")          # uses the default result
generate_screenshot("out.png", result=count_digit(digit=5, end=50))

Signature:

generate_screenshot(
    path: str = "Screenshots/home.png",
    result: DigitCount | None = None,
    font_size: int = 24,
    padding: int = 48,
) -> str

Returns the absolute path of the written file. Raises ImportError if Pillow is not installed.

Example

from h9a import count_digit, render_text

result = count_digit(digit=9, start=1, end=100)
print(render_text(result))

Back to Home