224. Python Program to Convert Roman Numerals to a Number
HardPhase 3 · Challenge
This one takes a few steps with a dictionary, a for loop over positions and if. You know all three. Try XIX on paper first.
Overview
This is the other half of a classic interview question. To read a Roman numeral, you look at each letter and at the letter right after it.
Problem Statement
Kwame reads old books. Their chapters have Roman numerals, the number system of ancient Rome. Kwame wants normal numbers instead.
Roman numerals use letters for numbers:
| Letter | Value |
|---|---|
| I | 1 |
| V | 5 |
| X | 10 |
| L | 50 |
| C | 100 |
| D | 500 |
| M | 1000 |
The rules:
- Most of the time, you add up the values of all the letters:
XVIis 10 + 5 + 1 = 16. - When a letter is smaller than the letter right after it, you take it away instead. In
IV, theIcomes before the biggerV, soIVis 5 - 1 = 4. In the same way,XCis 100 - 10 = 90.
The input is always a correct Roman numeral, so you do not need to check it.
Read a Roman numeral. Print <numeral> is <number>.
Examples
Example 1. Input MCMXCIV gives:
MCMXCIV is 1994
Why: M is 1000. The C comes before a bigger M, so CM is 900. XC is 90 and IV is 4. 1000 + 900 + 90 + 4 = 1994.
Example 2. Input LVIII gives:
LVIII is 58
Why: no letter is smaller than the letter after it, so you add them all: 50 + 5 + 1 + 1 + 1 = 58.
Input
One line with a correct Roman numeral in capital letters, for a number from 1 to 3999. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line: the numeral as it was typed, then is, then the number, with one space between the parts. The tests try 10 different inputs, also one letter and 3999.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.