Skip to content

Commit 6bff121

Browse files
authored
Update roman_numerals.py
1 parent 1735aed commit 6bff121

File tree

1 file changed

+7
-28
lines changed

1 file changed

+7
-28
lines changed

conversions/roman_numerals.py

+7-28
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,6 @@
2525
(4, "IV"),
2626
(1, "I"),
2727
]
28-
29-
3028
def roman_to_int(roman: str) -> int:
3129
"""
3230
Convert a Roman numeral to an integer, supporting Vinculum notation
@@ -42,44 +40,27 @@ def roman_to_int(roman: str) -> int:
4240
>>> all(roman_to_int(key) == value for key, value in tests.items())
4341
True
4442
"""
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
6144

6245
i, total = 0, 0
6346
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]]
6650
i += 2
6751
else:
6852
total += vals[roman[i]]
6953
i += 1
7054
return total
71-
72-
7355
def int_to_roman(number: int) -> str:
7456
"""
7557
Convert an integer to a Roman numeral, supporting Vinculum notation
7658
(underscore _ represents 1000 times).
7759
7860
Given an integer, convert it to a Roman numeral.
7961
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"}
8364
>>> all(int_to_roman(value) == key for key, value in tests.items())
8465
True
8566
"""
@@ -93,9 +74,7 @@ def int_to_roman(number: int) -> str:
9374
if number == 0:
9475
break
9576
return "".join(result)
96-
97-
77+
9878
if __name__ == "__main__":
9979
import doctest
100-
10180
doctest.testmod()

0 commit comments

Comments
 (0)