roman_to_int.py 765 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import re
  2. import pytest
  3. def romanToInt(s:str):
  4. special = {'IV': 4,
  5. 'IX': 9,
  6. 'XL': 40,
  7. 'XC': 90,
  8. 'CD': 400,
  9. 'CM': 900}
  10. single = {'I': 1,
  11. 'V': 5,
  12. 'X': 10,
  13. 'L': 50,
  14. 'C': 100,
  15. 'D': 500,
  16. 'M': 1000}
  17. r = 0
  18. for k, v in special.items():
  19. if k in s:
  20. r += v
  21. s = re.sub(k, '', s)
  22. print(s)
  23. for i in s:
  24. r += single[i]
  25. return r
  26. @pytest.mark.parametrize(
  27. "s, expect",
  28. [
  29. ('IV', 4),
  30. ('III', 3),
  31. ('LVIII', 58),
  32. ('MCMXCIV', 1994)
  33. ]
  34. )
  35. def test_cases(s, expect):
  36. assert romanToInt(s) == expect