roman to integer Algorithm

The Roman to Integer algorithm is a computational technique used to convert a Roman numeral string to its corresponding integer value. Roman numerals are a numeral system that was widely used in ancient Rome, and they are based on a combination of specific letters from the Latin alphabet: I, V, X, L, C, D, and M, which represent the numbers 1, 5, 10, 50, 100, 500, and 1000, respectively. The algorithm works by iterating through the Roman numeral string and adding the corresponding values of the characters, while also accounting for substractive notation, which is when a smaller numeral is placed before a larger numeral to signify subtraction. To implement the Roman to Integer algorithm, one can create a dictionary to map each Roman character to its corresponding integer value. The algorithm starts by initializing a variable to store the total integer value, and then iterates through the Roman numeral string from left to right. For each character, the algorithm compares its value to the value of the next character. If the current character's value is greater than or equal to the next character's value, the algorithm adds the current character's value to the total. If the current character's value is less than the next character's value, the algorithm subtracts the current character's value from the total instead. Once the iteration is complete, the algorithm returns the total as the final integer value representing the Roman numeral string.
def roman_to_int(roman: str) -> int:
    """
    LeetCode No. 13 Roman to Integer
    Given a roman numeral, convert it to an integer.
    Input is guaranteed to be within the range from 1 to 3999.
    https://en.wikipedia.org/wiki/Roman_numerals
    >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999}
    >>> all(roman_to_int(key) == value for key, value in tests.items())
    True
    """
    vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
    total = 0
    place = 0
    while place < len(roman):
        if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]):
            total += vals[roman[place + 1]] - vals[roman[place]]
            place += 2
        else:
            total += vals[roman[place]]
            place += 1
    return total


if __name__ == "__main__":
    import doctest

    doctest.testmod()

LANGUAGE:

DARK MODE: