File: self-dividing-numbers/solution.py

Date: 2026-06-06

Time: 19:02

Purpose

This file solves LeetCode 728 — Self Dividing Numbers. A self-dividing number is one that is divisible by every digit it contains, with the additional constraint that it cannot contain the digit zero (since division by zero is undefined). The file owns the complete solution: the predicate that tests a single number and the range filter that collects all matches.

Key Components

isselfdividing(n: int) -> bool

The core predicate. Extracts digits from n right-to-left using repeated % 10 / //= 10 and checks two conditions per digit:

1. The digit is not zero.

2. The original number n is evenly divisible by the digit.

Returns False on the first violation (short-circuit). Returns True only if every digit passes.

Note the use of two separate variables: num (the copy being consumed for digit extraction) and n (the original value used for the divisibility test). This is critical — if you tested num % digit instead, you'd be testing a shrinking number against its own digits, which is wrong.

selfdividingnumbers(left: int, right: int) -> list[int]

A thin range-filter wrapper. Iterates [left, right] inclusive and collects numbers satisfying isselfdividing. Implemented as a single list comprehension — no early termination or optimization, just a linear scan.

Patterns

Dependencies

Imports: None — pure stdlib, no external dependencies.

Imported by: The "Imported By" list in the prompt is misleading — those are test files across the entire repo that likely share a common test harness, not files that actually call isselfdividing or selfdividingnumbers. The real consumer is self-dividing-numbers/test_solution.py.

Flow


self_dividing_numbers(left=1, right=22)
  → range(1, 23)
  → for each n: is_self_dividing(n)
       n=1:  num=1 → digit=1, 1%1==0 ✓ → num=0 → True
       n=10: num=10 → digit=0 → False (zero digit)
       n=12: num=12 → digit=2, 12%2==0 ✓ → num=1 → digit=1, 12%1==0 ✓ → True
       n=22: num=22 → digit=2, 22%2==0 ✓ → num=2 → digit=2, 22%2==0 ✓ → True
  → [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]

Invariants

Error Handling

None. No exceptions are raised or caught. The function trusts its caller to provide valid positive integers. Division by zero is avoided at the logic level by checking digit == 0 before n % digit.

Topics to Explore

Beliefs