w3resource

Python: Convert a roman numeral to an integer


2. Convert a Roman Numeral to an Integer

Write a Python class to convert a Roman numeral to an integer.

Sample Solution:

Python Code:

class py_solution:
    def roman_to_int(self, s):
        rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        int_val = 0
        for i in range(len(s)):
            if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
                int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]]
            else:
                int_val += rom_val[s[i]]
        return int_val

print(py_solution().roman_to_int('MMMCMLXXXVI'))
print(py_solution().roman_to_int('MMMM'))
print(py_solution().roman_to_int('C'))

Sample Output:

3986                                                                                                          
4000                                                                                                          
100

Pictorial Presentation:

Python: Convert a roman numeral to an integer.

Flowchart:

Flowchart: Convert a roman numeral to an integer

For more Practice: Solve these Related Problems:

  • Write a Python class that maps Roman numeral characters to integer values and converts a Roman numeral string to an integer using a for-loop.
  • Write a Python class that implements a reverse-lookup algorithm to handle subtractive notation in Roman numerals when converting to an integer.
  • Write a Python class that validates Roman numeral input, ensuring it adheres to standard numeral rules before conversion.
  • Write a Python class that provides both iterative and recursive methods for converting a Roman numeral to an integer and compares their performance.

Go to:


Previous: Write a Python class to convert an integer to a roman numeral.
Next: Write a Python class to find validity of a string of parentheses, '(', ')', '{', '}', '[' and ']. These brackets must be close in the correct order,
for example "()" and "()[]{}" are valid but "[)", "({[)]" and "{{{" are invalid.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.