Skip to content

Commit 07721a8

Browse files
authored
Update roman_numerals.py
1 parent e6ea0ba commit 07721a8

File tree

1 file changed

+14
-42
lines changed

1 file changed

+14
-42
lines changed

conversions/roman_numerals.py

+14-42
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,11 @@
11
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")
278
]
28-
29-
309
def roman_to_int(roman):
3110
"""
3211
Convert a Roman numeral to an integer, supporting Vinculum notation
@@ -43,19 +22,14 @@ def roman_to_int(roman):
4322
True
4423
"""
4524
vals = {roman: arabic for arabic, roman in ROMAN}
46-
# Convert the list of tuples to a dictionary
47-
4825
i, total = 0, 0
4926
while i < len(roman):
50-
if i + 1 < len(roman) and roman[i : i + 2] in vals:
51-
total += vals[roman[i : i + 2]]
52-
i += 2
53-
else:
54-
total += vals[roman[i]]
55-
i += 1
56-
return total
57-
58-
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
5933
def int_to_roman(number):
6034
"""
6135
Convert an integer to a Roman numeral, supporting Vinculum notation
@@ -68,7 +42,7 @@ def int_to_roman(number):
6842
>>> all(int_to_roman(value) == key for key, value in tests.items())
6943
True
7044
"""
71-
if not isinstance(number, int) or number < 1:
45+
if not isinstance(number, int) or number <= 0:
7246
raise ValueError("Input must be a positive integer greater than 0")
7347

7448
result = []
@@ -78,9 +52,7 @@ def int_to_roman(number):
7852
if number == 0:
7953
break
8054
return "".join(result)
81-
82-
55+
8356
if __name__ == "__main__":
8457
import doctest
85-
8658
doctest.testmod()

0 commit comments

Comments
 (0)