
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to convert roman numeral to integer in Python?
Suppose we have a roman numeral; we have to convert it into number. As we know a Roman numeral is represented by symbols from left to right from greatest to least, the only exception being when representing one less than a symbol. Some roman numeral symbol meanings are as follows:
'M': 1000
'D': 500
'C': 100
'L': 50
'X': 10
'V': 5
'I': 1
So, if the input is like numeral = "MCLXVI", then the output will be 1166, as M = 1000, C = 100, total is 1100, then L = 50, X = 10, VI = 6 so total is 1166.
To solve this, we will follow these steps:
take numeral list as mentioned above
ans := 0
n := size of numeral
for each index idx and value c numeral, do
if idx < n - 1 and d[c] < d[numeral[idx + 1]], then
ans := ans - d[c]
otherwise,
ans := ans + d[c]
return ans
Let us see the following implementation to get better understanding:
Example
class Solution: def solve(self, numeral): d = {"M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1} ans = 0 n = len(numeral) for (idx, c) in enumerate(numeral): if idx < n - 1 and d[c] < d[numeral[idx + 1]]: ans -= d[c] else: ans += d[c] return ans ob = Solution() numeral = "MCLXVI" print(ob.solve(numeral))
Input
"MCLXVI"
Output
1166
- Related Articles
- Program to convert integer to roman numeral in Python
- JAVA Program To Convert Roman Number to Integer Number
- Roman to Integer in Python
- Value of Roman numeral M ?
- Integer to Roman in C
- Write the roman numeral of $567$.
- JavaScript program to convert positive integers to roman numbers
- C program to convert roman numbers to decimal numbers
- Convert Tuple to integer in Python
- Mention rule number 2 of the Roman numeral.
- How to convert float to integer in Python?
- Replace * by appropriate roman numeral, if $VLXXX*X = 5089$
- Program to convert Linked list representing binary number to decimal integer in Python
- Program to convert set of Integer to Array of Integer in Java
- Java Program to convert integer to octal
