Update roman_numerals.py

This commit is contained in:
lighting9999 2025-02-10 17:48:43 +08:00 committed by GitHub
parent 5e41453c5e
commit 657073d140
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,33 +1,12 @@
ROMAN = [ ROMAN = [
(1000000, "M_"), (1000000, "M_"), (900000, "C_M_"), (500000, "D_"), (400000, "C_D_"),
(900000, "C_M_"), (100000, "C_"), (90000, "X_C_"), (50000, "L_"), (40000, "X_L_"),
(500000, "D_"), (10000, "X_"), (9000, "I_X_"), (5000, "V_"), (4000, "I_V_"),
(400000, "C_D_"), (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
(100000, "C_"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
(90000, "X_C_"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")
(50000, "L_"),
(40000, "X_L_"),
(10000, "X_"),
(9000, "I_X_"),
(5000, "V_"),
(4000, "I_V_"),
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
] ]
def roman_to_int(roman):
def roman_to_int(roman: str) -> int:
""" """
Convert a Roman numeral to an integer, supporting Vinculum notation Convert a Roman numeral to an integer, supporting Vinculum notation
(underscore _ represents 1000 times). (underscore _ represents 1000 times).
@ -42,21 +21,20 @@ def roman_to_int(roman: str) -> int:
>>> all(roman_to_int(key) == value for key, value in tests.items()) >>> all(roman_to_int(key) == value for key, value in tests.items())
True True
""" """
vals = dict(ROMAN) # Convert the list of tuples to a dictionary vals = {roman: arabic for arabic, roman in ROMAN}
# Convert the list of tuples to a dictionary
i, total = 0, 0 i, total = 0, 0
while i < len(roman): while i < len(roman):
# Check for 2-character symbols first (like I_ or X_) # 先匹配 2 个字符的罗马数字(如 I_、X_
if i + 1 < len(roman) and roman[i : i + 2] in vals: if i + 1 < len(roman) and roman[i:i+2] in vals:
total += vals[roman[i : i + 2]] total += vals[roman[i:i+2]]
i += 2 i += 2
else: else:
total += vals[roman[i]] total += vals[roman[i]]
i += 1 i += 1
return total return total
def int_to_roman(number):
def int_to_roman(number: int) -> str:
""" """
Convert an integer to a Roman numeral, supporting Vinculum notation Convert an integer to a Roman numeral, supporting Vinculum notation
(underscore _ represents 1000 times). (underscore _ represents 1000 times).
@ -79,8 +57,6 @@ def int_to_roman(number: int) -> str:
break break
return "".join(result) return "".join(result)
if __name__ == "__main__": if __name__ == "__main__":
import doctest import doctest
doctest.testmod() doctest.testmod()