Convert numbers to roman numerals using Python
-
Roman Numerals are a number system used in ancient Rome. Numbers here are represented using a combination of letters. Modern style uses 7 symbols, each with different values. The largest number that can be written using these symbols are 3,999.
Symbol Integer Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 Numerals can be combined in different order to form numbers. See below roman numerals for numbers from 1 to 10 and some other 2 letter numerals for specific numbers.
I = 1
II = 2
III = 3
IV = 4
V = 5
VI = 6
VII = 7
VIII = 8
IX = 9
X = 10
XL = 40
XC = 90
CD = 40
CM = 900
Some other examples:
209 = CC + IX = CCIX
93 = XC + III = XCIII
1005 = M + V = MV
1045 = M + CD + V = MCDV -
Convert integer to roman numerals
As seen above, we represent certain numbers using a single letter. And for some numbers, we require a combination of 2 letters.
So we can use a simple logic to find the corresponding roman numeral of a number. We will keep the specific values of each of these characters in descending order in a tuple. Then loop through this tuple and find the matching characters. And reduce the number till reaches 0.
Consider an example for better understanding.
Input number = 1025
In the for loop, 1025 > first option (1000, 'M')
So, romannum = M, num = num-1000 = 25
Loop continues. (10, 'X') is the first option that satisfies the condition.
romannum = MX, num = num-10 = 15
Again 15 > 10. So, (10, 'X')
Now, romannum = MXX, num = num-10 = 5
Now last loop and (5, 'V') matches
So romannum = MXXV, num = num-5 = 0
Copieddef findRoman(num): valuesTuple = ( (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I') ) romannum = '' for i in valuesTuple: while num >= i[0]: romannum = romannum + i[1] num -= i[0] print(romannum) findRoman(3999) findRoman(2949)
MMMCMXCIX
MMCMXLIX