"roman numerals to integers converter with python using a dictionary" Code Answer

2

you have to make sure that you consume all characters that contribute to the sum. since all the multi-char "atomic" literals begin with the lower valued unit, and otherwise, higher valued units come first, a simple greedy approach is workable:

  • try to convert the first two chars as a whole, if that's not possible, convert the first single char.
  • move forward the appropriate number of steps.

    def roman_int(user_roman):
        user_roman = user_roman.upper()
        resulti = 0
    
        while user_roman:
            # try first two chars
            if user_roman[:2] in roman_numerals:
                resulti += roman_numerals[user_roman[:2]]
                # cut off first two chars
                user_roman = user_roman[2:]
            # try first char
            elif user_roman[:1] in roman_numerals:
                resulti += roman_numerals[user_roman[:1]]
                # cut off first char
                user_roman = user_roman[1:]
            else:
                print('no roman number')
                return
        print(resulti)
    
By Suraksha Ajith on August 28 2022

Answers related to “roman numerals to integers converter with python using a dictionary”

Only authorized users can answer the Search term. Please sign in first, or register a free account.