fork download
  1. import re
  2.  
  3. class Solution:
  4. def romanToInt(self, s: str) -> int:
  5. roman_numerals = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
  6. result = 0
  7. for i, c in enumerate(s):
  8. if (i + 1) == len(s) or roman_numerals[c] >= roman_numerals[s[i + 1]]:
  9. result += roman_numerals[c]
  10. else:
  11. result -= roman_numerals[c]
  12. if result == 0:
  13. return ''
  14. return result
  15.  
  16. 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'
  17.  
  18. text = """Римские числа: I, II, III, IV, V, VI, VII, VIII, IX, X,
  19. XII, XX, XXX, XL, L, XC, C, CD, D, CM, M, и даже MMMCMXCIX, и MMMM (не должно преобразоваться)."""
  20.  
  21. def replace_roman_with_arabic(text):
  22. solution = Solution()
  23.  
  24. def replacer(match):
  25. roman_numeral = match.group(0)
  26. arabic_value = solution.romanToInt(roman_numeral)
  27. return str(arabic_value)
  28.  
  29. return re.sub(regex, replacer, text)
  30.  
  31.  
  32. if __name__ == "__main__":
  33. new_text = replace_roman_with_arabic(text)
  34. print(new_text)
  35.  
Success #stdin #stdout 0.03s 9796KB
stdin
Standard input is empty
stdout
Римские числа: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
12, 20, 30, 40, 50, 90, 100, 400, 500, 900, 1000, и даже 3999, и MMMM (не должно преобразоваться).