Last active
May 26, 2023 12:39
-
-
Save 607011/f77b6f860b74053d331265c0ce238d3a to your computer and use it in GitHub Desktop.
Convert integer to Roman number literals
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
I2R = {1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 20: 'XX', 30: 'XXX', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 200: 'CC', 300: 'CCC', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M', 2000: 'MM', 3000: 'MMM'} | |
Candidates = [3000, 2000, 1000, 900, 500, 400, 300, 200, 100, 90, 50, 40, 30, 20, 10, 9, 5, 4, 3, 2, 1] | |
def int2roman(num: int) -> str: | |
roman = '' | |
while num > 0: | |
d = next(x for x in Candidates if num >= x) | |
num -= d | |
roman += I2R[d] | |
return roman |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment