Skip to main content
Added timing (results only) for Maarten Bodewes's code
Source Link
AJNeufeld
  • 35.3k
  • 5
  • 41
  • 103
somya_agrawal   1.288
ajneufeld       0.737
jg              1.521
jg2             1.324
maarten_bodewes 2.186
maarten_bodewes 1.653 (decode only)
somya_agrawal   1.288
ajneufeld       0.737
jg              1.521
jg2             1.324
somya_agrawal   1.288
ajneufeld       0.737
jg              1.521
jg2             1.324
maarten_bodewes 2.186
maarten_bodewes 1.653 (decode only)
"Longest" Roman numeral string was too short.
Source Link
AJNeufeld
  • 35.3k
  • 5
  • 41
  • 103

With 3999 as the maximum, the longest Roman numeral string would be 1215 characters ("MMMCCCXXXIII""MMMDCCCLXXXVIII"). Your last loop would iterate 1114 times, taking two letter substrings.

With 3999 as the maximum, the longest Roman numeral string would be 12 characters ("MMMCCCXXXIII"). Your last loop would iterate 11 times, taking two letter substrings.

With 3999 as the maximum, the longest Roman numeral string would be 15 characters ("MMMDCCCLXXXVIII"). Your last loop would iterate 14 times, taking two letter substrings.

Replaced CHECKS with SUBTRACTIVE as suggested in comments
Source Link
AJNeufeld
  • 35.3k
  • 5
  • 41
  • 103
CHECKSSUBTRACTIVE = {"IV": 2, "IX": 2, "XL": 20, "XC": 20, "CD": 200, "CM": 200}
VALUES = {"I": 1, "V": 5, "X":10, "L": 50, "C": 100, "D": 500, "M": 1000}

def roman_to_int(roman: str) -> int:
   
    number = sum(VALUES[ch] for ch in roman)
    number -= sum(val for key, val in CHECKSSUBTRACTIVE.items() if key in roman)

    return number

Although I'm not a fan ofAlthough I'm not a fan of CHECKS, but a better concise name is escaping me. Now using CHECKSSUBTRACTIVE, but a better concise name is escaping me as suggested by JollyJoker.

CHECKS = {"IV": 2, "IX": 2, "XL": 20, "XC": 20, "CD": 200, "CM": 200}
VALUES = {"I": 1, "V": 5, "X":10, "L": 50, "C": 100, "D": 500, "M": 1000}

def roman_to_int(roman: str) -> int:
   
    number = sum(VALUES[ch] for ch in roman)
    number -= sum(val for key, val in CHECKS.items() if key in roman)

    return number

Although I'm not a fan of CHECKS, but a better concise name is escaping me.

SUBTRACTIVE = {"IV": 2, "IX": 2, "XL": 20, "XC": 20, "CD": 200, "CM": 200}
VALUES = {"I": 1, "V": 5, "X":10, "L": 50, "C": 100, "D": 500, "M": 1000}

def roman_to_int(roman: str) -> int:
   
    number = sum(VALUES[ch] for ch in roman)
    number -= sum(val for key, val in SUBTRACTIVE.items() if key in roman)

    return number

Although I'm not a fan of CHECKS, but a better concise name is escaping me. Now using SUBTRACTIVE as suggested by JollyJoker.

Speed comparison between different methods
Source Link
AJNeufeld
  • 35.3k
  • 5
  • 41
  • 103
Loading
Spelling
Source Link
AJNeufeld
  • 35.3k
  • 5
  • 41
  • 103
Loading
Continued review; deleted 6 characters in body
Source Link
AJNeufeld
  • 35.3k
  • 5
  • 41
  • 103
Loading
Source Link
AJNeufeld
  • 35.3k
  • 5
  • 41
  • 103
Loading