import re
class Solution:
def romanToInt(self, s: str) -> int:
roman_numerals = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result = 0
for i, c in enumerate(s):
if (i + 1) == len(s) or roman_numerals[c] >= roman_numerals[s[i + 1]]:
result += roman_numerals[c]
else:
result -= roman_numerals[c]
if result == 0:
return ''
return result
regex = r'\b(M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3}))\b'
text = """Римские числа: I, II, III, IV, V, VI, VII, VIII, IX, X,
XII, XX, XXX, XL, L, XC, C, CD, D, CM, M, и даже MMMCMXCIX, и MMMM (не должно преобразоваться)."""
def replace_roman_with_arabic(text):
solution = Solution()
def replacer(match):
roman_numeral = match.group(0)
arabic_value = solution.romanToInt(roman_numeral)
return str(arabic_value)
return re.sub(regex, replacer, text)
if __name__ == "__main__":
new_text = replace_roman_with_arabic(text)
print(new_text)
aW1wb3J0IHJlCgpjbGFzcyBTb2x1dGlvbjoKICAgIGRlZiByb21hblRvSW50KHNlbGYsIHM6IHN0cikgLT4gaW50OgogICAgICAgIHJvbWFuX251bWVyYWxzID0geydJJzogMSwgJ1YnOiA1LCAnWCc6IDEwLCAnTCc6IDUwLCAnQyc6IDEwMCwgJ0QnOiA1MDAsICdNJzogMTAwMH0KICAgICAgICByZXN1bHQgPSAwCiAgICAgICAgZm9yIGksIGMgaW4gZW51bWVyYXRlKHMpOgogICAgICAgICAgICBpZiAoaSArIDEpID09IGxlbihzKSBvciByb21hbl9udW1lcmFsc1tjXSA+PSByb21hbl9udW1lcmFsc1tzW2kgKyAxXV06CiAgICAgICAgICAgICAgICByZXN1bHQgKz0gcm9tYW5fbnVtZXJhbHNbY10KICAgICAgICAgICAgZWxzZToKICAgICAgICAgICAgICAgIHJlc3VsdCAtPSByb21hbl9udW1lcmFsc1tjXQogICAgICAgIGlmIHJlc3VsdCA9PSAwOgogICAgICAgIAlyZXR1cm4gJycKICAgICAgICByZXR1cm4gcmVzdWx0CgpyZWdleCA9IHInXGIoTXswLDN9KENNfENEfEQ/Q3swLDN9KShYQ3xYTHxMP1h7MCwzfSkoSVh8SVZ8Vj9JezAsM30pKVxiJwoKdGV4dCA9ICIiItCg0LjQvNGB0LrQuNC1INGH0LjRgdC70LA6IEksIElJLCBJSUksIElWLCBWLCBWSSwgVklJLCBWSUlJLCBJWCwgWCwgClhJSSwgWFgsIFhYWCwgWEwsIEwsIFhDLCBDLCBDRCwgRCwgQ00sIE0sINC4INC00LDQttC1IE1NTUNNWENJWCwg0LggTU1NTSAo0L3QtSDQtNC+0LvQttC90L4g0L/RgNC10L7QsdGA0LDQt9C+0LLQsNGC0YzRgdGPKS4iIiIKCmRlZiByZXBsYWNlX3JvbWFuX3dpdGhfYXJhYmljKHRleHQpOgogICAgc29sdXRpb24gPSBTb2x1dGlvbigpCiAgICAKICAgIGRlZiByZXBsYWNlcihtYXRjaCk6CiAgICAgICAgcm9tYW5fbnVtZXJhbCA9IG1hdGNoLmdyb3VwKDApCiAgICAgICAgYXJhYmljX3ZhbHVlID0gc29sdXRpb24ucm9tYW5Ub0ludChyb21hbl9udW1lcmFsKQogICAgICAgIHJldHVybiBzdHIoYXJhYmljX3ZhbHVlKQoKICAgIHJldHVybiByZS5zdWIocmVnZXgsIHJlcGxhY2VyLCB0ZXh0KQoKCmlmIF9fbmFtZV9fID09ICJfX21haW5fXyI6CgluZXdfdGV4dCA9IHJlcGxhY2Vfcm9tYW5fd2l0aF9hcmFiaWModGV4dCkKCXByaW50KG5ld190ZXh0KQo=
Римские числа: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
12, 20, 30, 40, 50, 90, 100, 400, 500, 900, 1000, и даже 3999, и MMMM (не должно преобразоваться).