-
-
Notifications
You must be signed in to change notification settings - Fork 50.5k
Expand file tree
/
Copy pathinteger_to_roman.py
More file actions
52 lines (45 loc) · 1.04 KB
/
integer_to_roman.py
File metadata and controls
52 lines (45 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def integer_to_roman(number: int) -> str:
"""
Convert an integer to a Roman numeral.
Examples:
>>> integer_to_roman(1)
'I'
>>> integer_to_roman(4)
'IV'
>>> integer_to_roman(9)
'IX'
>>> integer_to_roman(58)
'LVIII'
>>> integer_to_roman(1994)
'MCMXCIV'
>>> integer_to_roman(0)
Traceback (most recent call last):
...
ValueError: number must be between 1 and 3999
"""
if not (1 <= number <= 3999):
raise ValueError("number must be between 1 and 3999")
symbols = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
]
result = []
for value, numeral in symbols:
while number >= value:
result.append(numeral)
number -= value
return "".join(result)
if __name__ == "__main__":
import doctest
doctest.testmod()