def fromRoman(r):
    """Return the numeric value of a valid roman numeral."""
    # Handle subtractions by trying to match two characters first.
    # If this fails, match only one character.
    romanMap = dict((('M', 1000), ('CM', 900), ('D', 500),
                     ('CD', 400), ('C', 100), ('XC', 90),
                     ('L', 50), ('XL', 40), ('X', 10),
                     ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)))
    num, i = 0, 0
    try:
        while i < len(r) - 1:
            if r[i:i+2] in romanMap:
                num += romanMap[r[i:i+2]]
                i += 2
            else:
                num += romanMap[r[i]]
                i += 1
        if i < len(r):
            num += romanMap[r[i]]
        return num
    except KeyError as e:
        raise ValueError('Bad roman numeral: ' + r)