Skip to content

Commit f4682f1

Browse files
authored
Update roman_numerals.py
1 parent 668b78a commit f4682f1

File tree

1 file changed

+9
-33
lines changed

1 file changed

+9
-33
lines changed

conversions/roman_numerals.py

+9-33
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,23 @@
11
ROMAN = [
2-
(1000000, "M_"), (900000, "C_M_"), (500000, "D_"), (400000, "C_D_"),
2+
(1000000, "M_"), (900000, "C_M_"), (500000, "D_"), (400000, "C_D_"),
33
(100000, "C_"), (90000, "X_C_"), (50000, "L_"), (40000, "X_L_"),
44
(10000, "X_"), (9000, "I_X_"), (5000, "V_"), (4000, "I_V_"),
55
(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
66
(100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
77
(10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")
88
]
99
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-
"""
2410
vals = {roman: arabic for arabic, roman in ROMAN}
2511
i, total = 0, 0
2612
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
3320
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-
"""
4521
if not isinstance(number, int) or number <= 0:
4622
raise ValueError("Input must be a positive integer greater than 0")
4723

@@ -52,7 +28,7 @@ def int_to_roman(number):
5228
if number == 0:
5329
break
5430
return "".join(result)
55-
31+
5632
if __name__ == "__main__":
5733
import doctest
5834
doctest.testmod()

0 commit comments

Comments
 (0)