Minimizing roman number to use substraction rule

TrustyTony 0 Tallied Votes 317 Views Share

Roman numbers is a standard programming exercise, to give it a small twist, we input roman numeral, turn it to value and prepare minimal version of it using the substraction rule.

Correctness of the input is not checked so Garbage in - Garbage out.

"""Given correct, but maybe not minimal Roman number, prepare the mimimal version from it's value"""

roman_values = (('I',1), ('IV',4), ('V',5), ('IX',9),('X',10),('XL',40),('L',50),('XC',90),('C',100),
                    ('CD', 400), ('D', 500), ('CM', 900), ('M',1000))

def romanvalue(roman):
    total=0
    romancopy = roman[:].upper()
    for symbol,value in reversed(roman_values):
        while romancopy.startswith(symbol):
            total += value
            romancopy = romancopy[len(symbol):]
    return total


def minimal(total):
    value = ''
    while total > 0:
        for symbol,symbol_value in reversed(roman_values):
            while total >= symbol_value:
                value += symbol
                total -= symbol_value
    return value

value = romanvalue(raw_input('Give roman number:'))
print('Minimal is: %s (value %i)' % (minimal(value), value))

""" Output:
Give roman number:xxxxiiii
Minimal is: XLIV (value 44)
"""