25
25
(4 , "IV" ),
26
26
(1 , "I" ),
27
27
]
28
-
29
-
30
28
def roman_to_int (roman : str ) -> int :
31
29
"""
32
30
Convert a Roman numeral to an integer, supporting Vinculum notation
@@ -42,44 +40,27 @@ def roman_to_int(roman: str) -> int:
42
40
>>> all(roman_to_int(key) == value for key, value in tests.items())
43
41
True
44
42
"""
45
- vals = {
46
- "I" : 1 ,
47
- "V" : 5 ,
48
- "X" : 10 ,
49
- "L" : 50 ,
50
- "C" : 100 ,
51
- "D" : 500 ,
52
- "M" : 1000 ,
53
- "I_" : 1000 ,
54
- "V_" : 5000 ,
55
- "X_" : 10000 ,
56
- "L_" : 50000 ,
57
- "C_" : 100000 ,
58
- "D_" : 500000 ,
59
- "M_" : 1000000 ,
60
- }
43
+ vals = dict (ROMAN ) # Convert the list of tuples to a dictionary
61
44
62
45
i , total = 0 , 0
63
46
while i < len (roman ):
64
- if i + 1 < len (roman ) and roman [i : i + 2 ] in vals :
65
- total += vals [roman [i : i + 2 ]]
47
+ # Check for 2-character symbols first (like I_ or X_)
48
+ if i + 1 < len (roman ) and roman [i :i + 2 ] in vals :
49
+ total += vals [roman [i :i + 2 ]]
66
50
i += 2
67
51
else :
68
52
total += vals [roman [i ]]
69
53
i += 1
70
54
return total
71
-
72
-
73
55
def int_to_roman (number : int ) -> str :
74
56
"""
75
57
Convert an integer to a Roman numeral, supporting Vinculum notation
76
58
(underscore _ represents 1000 times).
77
59
78
60
Given an integer, convert it to a Roman numeral.
79
61
80
- Reference:https://en.wikipedia.org/wiki/Roman_numerals
81
- >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500,
82
- ... "MMMCMXCIX": 3999, "I_V_": 4000, "X_": 10000, "M_": 1000000}
62
+ Reference: https://en.wikipedia.org/wiki/Roman_numerals
63
+ >>> tests = {3: "III", 154: "CLIV", 1009: "MIX", 2500: "MMD", 3999: "MMMCMXCIX"}
83
64
>>> all(int_to_roman(value) == key for key, value in tests.items())
84
65
True
85
66
"""
@@ -93,9 +74,7 @@ def int_to_roman(number: int) -> str:
93
74
if number == 0 :
94
75
break
95
76
return "" .join (result )
96
-
97
-
77
+
98
78
if __name__ == "__main__" :
99
79
import doctest
100
-
101
80
doctest .testmod ()
0 commit comments