Advertisement
acclivity

pyRomanNumerals2Integer

Aug 31st, 2023
736
1
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.91 KB | Software | 1 0
  1. # Convert Roman Numerals To Integer
  2. # Mike Kerry - December 2020, August 2023 - [email protected]
  3.  
  4. def convert_roman_to_int(s):
  5.     roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
  6.     result, prev = 0, 0
  7.     for c in s.upper():         # iterate through Roman Numeral string
  8.         v = roman[c]            # Get value of current character
  9.         if v > prev:            # is the current letter value greater than the previous? ...
  10.             result -= 2*prev    # ... yes, e.g. IX we had already added 1 but should have deducted 1
  11.         result += v             # add value of this letter to result
  12.         prev = v                # remember value of latest letter
  13.     return result
  14.  
  15.  
  16. tests = ["MMDCXL", "MCCCXLIX", "CDXXXVIII"]
  17.  
  18. for t in tests:
  19.     ps = convert_roman_to_int(t)
  20.     print(t, " = ", ps)
  21.  
  22.  
  23. # Results:-
  24. # MMDCXL  =  2640
  25. # MCCCXLIX  =  1349
  26. # CDXXXVIII  =  438
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement