1
1
ROMAN = [
2
- (1000000 , "M_" ),
3
- (900000 , "C_M_" ),
4
- (500000 , "D_" ),
5
- (400000 , "C_D_" ),
6
- (100000 , "C_" ),
7
- (90000 , "X_C_" ),
8
- (50000 , "L_" ),
9
- (40000 , "X_L_" ),
10
- (10000 , "X_" ),
11
- (9000 , "I_X_" ),
12
- (5000 , "V_" ),
13
- (4000 , "I_V_" ),
14
- (1000 , "M" ),
15
- (900 , "CM" ),
16
- (500 , "D" ),
17
- (400 , "CD" ),
18
- (100 , "C" ),
19
- (90 , "XC" ),
20
- (50 , "L" ),
21
- (40 , "XL" ),
22
- (10 , "X" ),
23
- (9 , "IX" ),
24
- (5 , "V" ),
25
- (4 , "IV" ),
26
- (1 , "I" ),
2
+ (1000000 , "M_" ), (900000 , "C_M_" ), (500000 , "D_" ), (400000 , "C_D_" ),
3
+ (100000 , "C_" ), (90000 , "X_C_" ), (50000 , "L_" ), (40000 , "X_L_" ),
4
+ (10000 , "X_" ), (9000 , "I_X_" ), (5000 , "V_" ), (4000 , "I_V_" ),
5
+ (1000 , "M" ), (900 , "CM" ), (500 , "D" ), (400 , "CD" ),
6
+ (100 , "C" ), (90 , "XC" ), (50 , "L" ), (40 , "XL" ),
7
+ (10 , "X" ), (9 , "IX" ), (5 , "V" ), (4 , "IV" ), (1 , "I" )
27
8
]
28
-
29
-
30
9
def roman_to_int (roman ):
31
10
"""
32
11
Convert a Roman numeral to an integer, supporting Vinculum notation
@@ -47,16 +26,13 @@ def roman_to_int(roman):
47
26
48
27
i , total = 0 , 0
49
28
while i < len (roman ):
50
- # 先匹配 2 个字符的罗马数字(如 I_、X_)
51
- if i + 1 < len (roman ) and roman [i : i + 2 ] in vals :
52
- total += vals [roman [i : i + 2 ]]
29
+ if i + 1 < len (roman ) and roman [i :i + 2 ] in vals :
30
+ total += vals [roman [i :i + 2 ]]
53
31
i += 2
54
32
else :
55
33
total += vals [roman [i ]]
56
34
i += 1
57
35
return total
58
-
59
-
60
36
def int_to_roman (number ):
61
37
"""
62
38
Convert an integer to a Roman numeral, supporting Vinculum notation
@@ -79,9 +55,7 @@ def int_to_roman(number):
79
55
if number == 0 :
80
56
break
81
57
return "" .join (result )
82
-
83
-
58
+
84
59
if __name__ == "__main__" :
85
60
import doctest
86
-
87
61
doctest .testmod ()
0 commit comments