diff --git a/test_utils.py b/test_utils.py index 5a264b2..dd29733 100644 --- a/test_utils.py +++ b/test_utils.py @@ -30,3 +30,23 @@ def test_multiply(a, b, expected): def test_divide(a, b, expected): result = utils.divide(a, b) assert result == expected + + +@pytest.mark.parametrize( + "n, expected", + [(0, "0b0"), (1, "0b1"), (2, "0b10"), (10, "0b1010"), (100, "0b1100100")], +) +def test_to_binary_valid(n, expected): + assert utils.to_binary(n) == expected + + +@pytest.mark.parametrize("n", [-1, 101, 999]) +def test_to_binary_out_of_range(n): + with pytest.raises(ValueError): + utils.to_binary(n) + + +@pytest.mark.parametrize("n", [1.5, "10", None]) +def test_to_binary_not_natural(n): + with pytest.raises(TypeError): + utils.to_binary(n) diff --git a/utils.py b/utils.py index 4a1de3e..11b8ffb 100644 --- a/utils.py +++ b/utils.py @@ -21,3 +21,12 @@ def multiply(a: int, b: int) -> int: def divide(a: int, b: int) -> float: """Divide the first integer by the second and return the result as a float.""" return a / b + + +def to_binary(n: int) -> str: + """Convert a natural number (0–100) to binary string. Raise if invalid.""" + if not isinstance(n, int): + raise TypeError("Input must be an integer.") + if not 0 <= n <= 100: + raise ValueError("Input must be in range 0 to 100.") + return bin(n)