Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
9 changes: 9 additions & 0 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)