Created
October 24, 2020 10:29
-
-
Save vkbo/739b8eac77c291c37436994671b94548 to your computer and use it in GitHub Desktop.
Simple Python function to convert an integer to a Roman number.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def numberToRoman(numVal, isLower=False): | |
"""Convert an integer to a roman number. | |
""" | |
if not isinstance(numVal, int): | |
return "NAN" | |
if numVal < 1 or numVal > 4999: | |
return "OOR" | |
theValues = [ | |
(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"), | |
] | |
romNum = "" | |
for theDiv, theSym in theValues: | |
n = numVal//theDiv | |
romNum += n*theSym | |
numVal -= n*theDiv | |
if numVal <= 0: | |
break | |
return romNum.lower() if isLower else romNum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment