Skip to content

Commit e510a03

Browse files
authored
fix: int_to_roman silently returns wrong values for out-of-range input
Added input validation for int_to_roman function.
1 parent 791deb4 commit e510a03

1 file changed

Lines changed: 26 additions & 1 deletion

File tree

conversions/roman_numerals.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,37 @@ def roman_to_int(roman: str) -> int:
4040

4141
def int_to_roman(number: int) -> str:
4242
"""
43-
Given a integer, convert it to an roman numeral.
43+
Given an integer, convert it to a Roman numeral.
44+
Input must be an integer in the range 1 to 3999.
4445
https://en.wikipedia.org/wiki/Roman_numerals
4546
>>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999}
4647
>>> all(int_to_roman(value) == key for key, value in tests.items())
4748
True
49+
>>> int_to_roman(0)
50+
Traceback (most recent call last):
51+
...
52+
ValueError: int_to_roman only accepts integers in the range 1 to 3999, got 0
53+
>>> int_to_roman(-1)
54+
Traceback (most recent call last):
55+
...
56+
ValueError: int_to_roman only accepts integers in the range 1 to 3999, got -1
57+
>>> int_to_roman(4000)
58+
Traceback (most recent call last):
59+
...
60+
ValueError: int_to_roman only accepts integers in the range 1 to 3999, got 4000
61+
>>> int_to_roman(True)
62+
Traceback (most recent call last):
63+
...
64+
TypeError: int_to_roman only accepts integers, got bool
4865
"""
66+
if not isinstance(number, int) or isinstance(number, bool):
67+
raise TypeError(
68+
f"int_to_roman only accepts integers, got {type(number).__name__}"
69+
)
70+
if not 1 <= number <= 3999:
71+
raise ValueError(
72+
f"int_to_roman only accepts integers in the range 1 to 3999, got {number}"
73+
)
4974
result = []
5075
for arabic, roman in ROMAN:
5176
(factor, number) = divmod(number, arabic)

0 commit comments

Comments
 (0)