File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ def integer_to_roman (n : int ) -> str :
2+ """
3+ Convert an integer to a Roman numeral.
4+
5+ Examples:
6+ >>> integer_to_roman(1)
7+ 'I'
8+ >>> integer_to_roman(4)
9+ 'IV'
10+ >>> integer_to_roman(9)
11+ 'IX'
12+ >>> integer_to_roman(58)
13+ 'LVIII'
14+ >>> integer_to_roman(1994)
15+ 'MCMXCIV'
16+ >>> integer_to_roman(0)
17+ Traceback (most recent call last):
18+ ...
19+ ValueError: number must be between 1 and 3999
20+ """
21+ if not (1 <= n <= 3999 ):
22+ raise ValueError ("number must be between 1 and 3999" )
23+
24+ symbols = [
25+ (1000 , "M" ),
26+ (900 , "CM" ),
27+ (500 , "D" ),
28+ (400 , "CD" ),
29+ (100 , "C" ),
30+ (90 , "XC" ),
31+ (50 , "L" ),
32+ (40 , "XL" ),
33+ (10 , "X" ),
34+ (9 , "IX" ),
35+ (5 , "V" ),
36+ (4 , "IV" ),
37+ (1 , "I" ),
38+ ]
39+
40+ result = []
41+ for value , numeral in symbols :
42+ while n >= value :
43+ result .append (numeral )
44+ n -= value
45+
46+ return "" .join (result )
47+
48+
49+ if __name__ == "__main__" :
50+ import doctest
51+ doctest .testmod ()
You can’t perform that action at this time.
0 commit comments