Created
February 12, 2016 22:52
-
-
Save bcambel/90131e1001c0b35e82a5 to your computer and use it in GitHub Desktop.
Convert numbers to Roman numbers
This file contains hidden or 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
| import math | |
| def digit(digits,num, n, upper, outlier, lower): | |
| multip = math.pow(10,n) | |
| if num >= multip: | |
| hundreds = int(num / multip) | |
| if hundreds == 9: | |
| digits.append(lower+upper) | |
| num -= (9 * multip) | |
| elif hundreds > 4: | |
| digits.append(outlier) | |
| num -= (5 * multip) | |
| elif hundreds == 4: | |
| digits.append(lower+outlier) | |
| num -= (4 * multip) | |
| for i in range(int(num/multip)): | |
| digits.append(lower) | |
| num-= multip | |
| return num, digits | |
| def intToRoman(num): | |
| digits = [] | |
| thousands = int(num / 1000) | |
| if thousands > 0: | |
| [digits.append("M") for i in range(thousands)] | |
| num = num - (1000 * thousands) | |
| num, digits = digit(digits, num, 2, 'M', 'D','C') | |
| num, digits = digit(digits, num, 1, 'C', 'L','X') | |
| num, digits = digit(digits, num, 0, 'X', 'V','I') | |
| return "".join(digits) | |
| print 554, intToRoman(554) | |
| print 449, intToRoman(449) | |
| print 1, intToRoman(1) | |
| print 114, intToRoman(114) | |
| print 1114, intToRoman(1114) | |
| print 1914, intToRoman(1914) | |
| print 1994, intToRoman(1994) | |
| print 1984, intToRoman(1984) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment