Coding Dojo

Edit on Gitlab

Kata Roman Numerals

Feel free to create a merge request on the codingdojo repository to suggest your own solution.


This is the most readable solution of the Roman Numerals Kata downloaded on this website.

#!/usr/bin/env python

def number_to_numeral(number):
    >>> number_to_numeral(1)
    >>> number_to_numeral(2)
    >>> number_to_numeral(12)
    >>> number_to_numeral(10)
    >>> number_to_numeral(20)
    >>> number_to_numeral(99)
    >>> number_to_numeral(100)
    >>> number_to_numeral(199)
    >>> number_to_numeral(2399)
    >>> number_to_numeral(4000)
    Traceback (most recent call last):
    IndexError: list index out of range


    numerals_dict = {
        'ones':     ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'],
        'tens':     ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'],
        'hundreds': ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'],
        'thousands': ['', 'M', 'MM', 'MMM'],

    s = []
    for index in ['ones', 'tens', 'hundreds', 'thousands']:
        number, remainder = divmod(number, 10)
        s.insert(0, numerals_dict[index][remainder])
    return ''.join(s)