Integer to roman numeral
Introduction
Roman numerals are a writing system for natural numbers (= positve integers) by using a combination of latin letters as symbols with a fixed integer value assigned to each symbol.
There are 7 symbols and their assigned integer values are:
M = 1000, D = 500, C = 100, L = 50, X = 10, V = 5, I = 1
While the conversion of a roman numeral is in its most simple form just the sum of the integer values e.g.
CXXIII = 100 + 10 + 10 + 1 + 1 + 1 = 123
a few additional rules must be observed:
The symbols are sorted from higher to lower values from left to right (e.g. IIIXXC is not a valid roman numeral)
A maximum of three of the same symbols can be used together. Numbers like 4 are represented by the ‘subtractive notation’ IV = -1 + 5 = 4 instead of IIII = 1 + 1 + 1 + 1 = 4, which is an exception to the rule above, because here the lower valued symbol precedes the higher valued one.
Note that the smallest valid roman number is I = 1, the highest one is MMMCMXCIX = 3999, there are no negative values, and there is no symbol for zero.
Exercise
Approach
Create a dict with the 7 single-letter and the 6 double-letter symbols sorted with decending values. Iterate over the dict and
Complete the function that converts an integer to a roman numeral
Know how
Iterating over a dict
Though the data type of a dict is a mapping and not a sequence like str, tuple and list it can be seen as a sequence of key / value pairs. The most noticable difference between a mapping and a sequence is that a dict’s value can only be accessed by its key and not by its index. Since Python 3.7 the order is even predictable (new elements will be appended at the end).
Iterate over the keys of the dict
Since the solution above only returns the keys of the dict an extra step is required to get the values as well.
Iterate over the keys of the dict and get the values
An alternative solution is to use the .items() method of the dict class.
Iterate over the keys and values of the dict
Go to solution.