1
1
ROMAN = [
2
- (1000000 , "M_" ), (900000 , "C_M_" ), (500000 , "D_" ), (400000 , "C_D_" ),
2
+ (1000000 , "M_" ), (900000 , "C_M_" ), (500000 , "D_" ), (400000 , "C_D_" ),
3
3
(100000 , "C_" ), (90000 , "X_C_" ), (50000 , "L_" ), (40000 , "X_L_" ),
4
4
(10000 , "X_" ), (9000 , "I_X_" ), (5000 , "V_" ), (4000 , "I_V_" ),
5
5
(1000 , "M" ), (900 , "CM" ), (500 , "D" ), (400 , "CD" ),
6
6
(100 , "C" ), (90 , "XC" ), (50 , "L" ), (40 , "XL" ),
7
7
(10 , "X" ), (9 , "IX" ), (5 , "V" ), (4 , "IV" ), (1 , "I" )
8
8
]
9
9
def roman_to_int (roman ):
10
- """
11
- Convert a Roman numeral to an integer, supporting Vinculum notation
12
- (underscore _ represents 1000 times).
13
-
14
- LeetCode No. 13 Roman to Integer:
15
- Given a Roman numeral, convert it to an integer.
16
- Input is guaranteed to be within the range from 1 to 3999.
17
-
18
- Reference: https://en.wikipedia.org/wiki/Roman_numerals
19
- >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500,
20
- ... "MMMCMXCIX": 3999, "I_V_": 4000, "X_": 10000, "M_": 1000000}
21
- >>> all(roman_to_int(key) == value for key, value in tests.items())
22
- True
23
- """
24
10
vals = {roman : arabic for arabic , roman in ROMAN }
25
11
i , total = 0 , 0
26
12
while i < len (roman ):
27
- if i + 1 < len (roman ) and roman [i + 1 ] == "_" :
28
- total += vals [roman [i ] + "_" ]
29
- i += 2
30
- else :
31
- total += vals [roman [i ]]
32
- i += 1
13
+ if i + 1 < len (roman ) and roman [i + 1 ] == "_" :
14
+ total += vals [roman [i ] + "_" ]
15
+ i += 2
16
+ else :
17
+ total += vals [roman [i ]]
18
+ i += 1
19
+ return total
33
20
def int_to_roman (number ):
34
- """
35
- Convert an integer to a Roman numeral, supporting Vinculum notation
36
- (underscore _ represents 1000 times).
37
-
38
- Given an integer, convert it to a Roman numeral.
39
-
40
- Reference: https://en.wikipedia.org/wiki/Roman_numerals
41
- >>> tests = {3: "III", 154: "CLIV", 1009: "MIX", 2500: "MMD", 3999: "MMMCMXCIX"}
42
- >>> all(int_to_roman(value) == key for key, value in tests.items())
43
- True
44
- """
45
21
if not isinstance (number , int ) or number <= 0 :
46
22
raise ValueError ("Input must be a positive integer greater than 0" )
47
23
@@ -52,7 +28,7 @@ def int_to_roman(number):
52
28
if number == 0 :
53
29
break
54
30
return "" .join (result )
55
-
31
+
56
32
if __name__ == "__main__" :
57
33
import doctest
58
34
doctest .testmod ()
0 commit comments