pysnippets.numbers.digitize
Split a number into its digits
digitize(n: int) -> list[int]
Turn an integer into a list of its decimal digits.
Checksums, digit sums and number puzzles all start here.
digitize.py✓ ruff · mypy --strict
def digitize(n: int) -> list[int]:
"""Return the decimal digits of ``n``, ignoring its sign."""
return [int(digit) for digit in str(abs(n))]- str(-405) has a "-" that int() can't parse, so drop the sign first
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> digitize(123)[1, 2, 3]passed on Python 3.11 to 3.14: >>> digitize(-405)[4, 0, 5]passed on Python 3.11 to 3.14: >>> digitize(0)[0]Edit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).
python 3.14 · in your browser
Loading Python 3.14 in your browser (≈7 MB, cached after the first time)…
Tab inserts four spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the examples.
How it works
str()gives the decimal digits as text.abs()comes first:int('-')would raise.- Each character converts back with
int().
Complexity: O(d) time and space for d digits
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from pysnippets.numbers.digitize import digitizeNo dependencies: copy digitize.py into your project, or clone the repo.Adapted from digitize in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Handles negative numbers; typed. Suggest an edit.