livepython.net

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:

LetterValue
I1
V5
X10
L50
C100
D500
M1000

The rules:

  • Most of the time, you add up the values of all the letters: XVI is 10 + 5 + 1 = 16.
  • When a letter is smaller than the letter right after it, you take it away instead. In IV, the I comes before the bigger V, so IV is 5 - 1 = 4. In the same way, XC is 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.

Finish this chapter firstChapter 13 · Dictionaries
solution.py
# write your code here

EXPECTED OUTPUT

1MCMXCIV is 1994

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.