Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
while, divmod, dict solution in Clear category for Roman Numerals by sudee
def roman_digit(digit, exponent):
"""
Takes a digit and an exponent and returns the corresponding
roman numeral using the defined map.
E.g.
7, 0 (7 * 10**0) -> VII
2, 3 (2 * 10**3) -> CC
"""
roman_digits = {1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M'}
place = 10**exponent
if digit in [0,1,2,3]:
return roman_digits[place] * digit
elif digit is 4:
return roman_digits[place] + roman_digits[5 * place]
elif digit in [5,6,7,8]:
return roman_digits[5 * place] + roman_digits[place] * (digit - 5)
elif digit is 9:
return roman_digits[place] + roman_digits[10 * place]
def checkio(number):
"""
Divides a number by 10 and passes the remainder as a digit
along with an increasing exponent to the roman_digit function.
Converts the number from the lowest place (ones) to the highest (thousands),
i.e. builds the resulting roman number from right to left.
"""
roman_number = ''
exponent = 0
while number >= 1:
number, digit = divmod(number, 10)
roman_number = roman_digit(digit, exponent) + roman_number
exponent += 1
return roman_number
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio(6) == 'VI', '6'
assert checkio(76) == 'LXXVI', '76'
assert checkio(499) == 'CDXCIX', '499'
assert checkio(1049)== 'MXLIX', '1049'
assert checkio(3888) == 'MMMDCCCLXXXVIII', '3888'
print('Done! Go Check!')
Aug. 14, 2018