46 lines
990 B
Python
46 lines
990 B
Python
roman_symbol = [
|
|
[ "IV", 4 ],
|
|
[ "IX", 9 ],
|
|
[ "XL", 40 ],
|
|
[ "XC", 90 ],
|
|
[ "CD", 400 ],
|
|
[ "CM", 900 ],
|
|
[ "I", 1 ],
|
|
[ "V", 5 ],
|
|
[ "X", 10 ],
|
|
[ "L", 50 ],
|
|
[ "C", 100 ],
|
|
[ "D", 500 ],
|
|
[ "M", 1000]
|
|
]
|
|
|
|
# Convert an integer to its roman representation as string
|
|
def int_to_roman(i):
|
|
s = ""
|
|
for rs in sorted(roman_symbol, key=lambda x: x[1], reverse=True):
|
|
count = i // rs[1]
|
|
s += rs[0] * count
|
|
if count > 0:
|
|
i %= rs[1] * count
|
|
|
|
return s
|
|
|
|
# Convert a roman number to its integer value; return 0 on error
|
|
def roman_to_int(s):
|
|
i = 0
|
|
su = s.upper()
|
|
while len(su) > 0:
|
|
for rs in roman_symbol:
|
|
if su.startswith(rs[0]):
|
|
break
|
|
else:
|
|
return 0
|
|
|
|
i += rs[1]
|
|
su = su.removeprefix(rs[0])
|
|
|
|
if s.upper() != int_to_roman(i):
|
|
return 0
|
|
|
|
return i
|