DEV Community

Cover image for Roman Numerals Decoder Codewars
He Codes IT
He Codes IT

Posted on

Roman Numerals Decoder Codewars

Today we will solve a Coding Problem, “Roman Numerals Decoder”, designed by Codewars in Python. In this Problem, we are given a String of Roman as Input, and we need to output an integer corresponding to that Roman Number. We Solved a similar Problem related to this where we converted Integers into Roman. You can read that Post here

Description of Roman Numerals Decoder Problem
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don’t need to validate the form of the Roman numeral.

Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered “MCMXC” (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered “MMVIII” (2000 = MM, 8 = VIII). The Roman numeral for 1666, “MDCLXVI”, uses each letter in descending order.


Input : XXIX
Output : 29

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
How do you decode Roman numerals?
Every symbol in Roman has a value associated with it. For example, X has a value of 10. Similarly, V has a value of 5. You need to add all the associated values, and you will get the number. For example, XXV where X=10 and V=5. Adding X+X+V = 10+10+5 = 25. But the Problem Arises when you have numbers like 4, 9, 40, etc. 9 is represented as IX in Roman, but if we apply the above technique. We will get I + X = 1 + 10 = 11. It is not Correct. When decoding Roman numerals, one thing to keep in mind is that, whenever the previous character in Roman is less than the current, we must subtract instead of Add. For Example, 4 is represented as IV in Roman, I has the value of 1, and V has a value of 5. so IV = 1 – 5 = abs(-4) = 4

Now let’s get to the Coding Part.

Roman Numerals Decoder Codewars Python Solution
Firstly, create a dictionary storing each Roman character along with its value.

def solution(roman):
symbol = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
then, create two variables one for storing the total sum and other for storing the previous value.

To read more visit

Top comments (0)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git