
mapping = {
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000
}


def roman_numeral(s):
    total = 0
    partial = mapping[s[-1]]
    i = len(s) - 2
    while i >= 0:
        digit = mapping[s[i]]
        if mapping[s[i + 1]] > digit:
            partial -= digit
        else:
            total += partial
            partial = digit
        i -= 1

    return total + partial


if __name__ == '__main__':
    print roman_numeral('MCMLXXXVI')
