livepython.net

223. Python Program to Convert a Number to Roman Numerals

HardPhase 3 · Challenge

This one takes a few steps. It uses two lists, a for loop and a while loop. You know all of them. Try a short example on paper first.

Overview

Roman numerals are the number system of ancient Rome. You still see them on clocks, in book chapters and in the years at the end of films. Turning numbers into them is a classic interview question.

Problem Statement

Sofia makes clock faces and book covers. Sofia needs numbers written in Roman numerals.

Roman numerals use letters for numbers:

LetterValue
I1
V5
X10
L50
C100
D500
M1000

The rules:

  • Write the letters from the biggest value to the smallest, and add them up: XVI is 10 + 5 + 1 = 16.
  • A letter can repeat up to 3 times in a row: III is 3, and XXX is 30.
  • Six numbers put a smaller letter before a bigger one. This means "take the small one away": IV is 4, IX is 9, XL is 40, XC is 90, CD is 400 and CM is 900. So 4 is IV, never IIII.

Read a number. Print <number> in Roman numerals is <numeral>.

Examples

Example 1. Input 1994 gives:

1994 in Roman numerals is MCMXCIV

Why: 1994 is 1000 + 900 + 90 + 4. That is M, then CM, then XC, then IV.

Example 2. Input 58 gives:

58 in Roman numerals is LVIII

Why: 58 is 50 + 5 + 3. That is L, then V, then III.

Input

One whole 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 number, then in Roman numerals is, then the Roman numeral in capital letters, with one space between the parts. The tests try 10 different inputs, also 1, 4, 9 and 3999.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 11 · While Loops
solution.py
# write your code here

EXPECTED OUTPUT

11994 in Roman numerals is MCMXCIV

YOUR OUTPUT

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