Show that "ans += resultList[i] - 2 * resultList[i-1]" in the function is the right expression to use when trying to convert ROMAN NUMBERS to INTEGERS

32 Views Asked by At

I was looking for creative ways in which someone could convert a valid roman number to an integer via algorithms in the web, and from all of the examples I found, there was one in particular that caught my attention because of the way it made it, it was a program built on Python which used a single function called roman_to_int that took the input of the user as the variable roman_string to use as argument in the function, see below:

#!/usr/bin/python3
def roman_to_int(roman_string):
    if not isinstance(roman_string, str) or roman_string is None:
        return 0

    numberDict = {
        "I": 1, "V": 5, "X": 10,
        "L": 50, "C": 100, "D": 500, "M": 1000
    }
    resultList = []
    for val in roman_string:
        for key, value in numberDict.items():
            if val == key:
                resultList.append(value)
    print(resultList)
    nElem = len(resultList)
    if nElem <= 0:
        return None
    ans = 0
    for i in range(nElem):
        if i > 0 and resultList[i] > resultList[i-1]:
            ans += resultList[i] - 2 * resultList[i-1]
        else:
            ans += resultList[i]
    return ans

So, if wanted to print the conversion of the roman number like MMMC to integer using this function, I use following the sentence:

print(roman_to_int('MMMC'))

Which would print:

3100

Which is correct. Another correct output also happens with MMMMMDCCC:

5800

Etc...

Now, keep in mind that I understand how the function above works, but I don't get why does the function substract 2 times the value at the previous position in the array resultList from the value at current position in the array resultList

(i.e. ans += resultList[i] - 2 * resultList[i-1])

Unfortunately, I'm too uneducated to type my question in a valid Math Notation, can someone assist me?

1

There are 1 best solutions below

2
On BEST ANSWER

The line of code ans += resultList[i] - 2 * resultList[i-1] only executes when resultList[i] > resultList[i-1] , which doesn't happen often in roman numbers.

In fact, this is done do cover the case like IX being meant to represent the number $9$. If you get IX, you will

  1. Add $1$, because you first process the character I
  2. Then you notice that the next character is X representing $10$.
  3. Because $10>1$, you now know that you added $1$ too many, so you need to subtract $1$, and you also need to add $10-1$. So alltogether you need to add $10 - 1$, and also subtract $-1$, so you need to add $10-2\cdot 1$.

The same applies if you meed something like $CM$. Again, you first add $100$, then add $1000-2\cdot 100$.