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?
The line of code
ans += resultList[i] - 2 * resultList[i-1]only executes whenresultList[i] > resultList[i-1], which doesn't happen often in roman numbers.In fact, this is done do cover the case like
IXbeing meant to represent the number $9$. If you getIX, you willIXrepresenting $10$.The same applies if you meed something like $CM$. Again, you first add $100$, then add $1000-2\cdot 100$.