Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Reverse Roman Numerals by MarcAureleCoste
from enum import Enum
class REVERSE_NUM(Enum):
"""Enum to convert roman charactere to decimal value."""
I = 1
V = 5
X = 10
L = 50
C = 100
D = 500
M = 1000
def reverse_roman(roman_string):
"""Convert a roman string to decimal value.
If the value for your current element is higher than the value of the
preceding element you must subtract this element to your current one.
"""
result = 0
prev_value = 0
for c in roman_string:
if not prev_value:
# No value stored in prev_value -> just put the current_value inside
prev_value = REVERSE_NUM[c].value
else:
# prev_value is filled -> two possible case
current_value = REVERSE_NUM[c].value
if prev_value >= current_value:
# Case 1 : previous value is higher or equal, just add the
# previous value to you result and move the current value to
# previous value
result += prev_value
prev_value = current_value
else:
# Case 2 : previous value is lower, in this case subtract this
# previous value to your current value, put this in your result
# and reset the previous value.
result += current_value - prev_value
prev_value = 0
result += prev_value
return result
if __name__ == "__main__":
# These "asserts" using only for self-checking and not necessary for auto-testing
assert reverse_roman("VI") == 6, "6"
assert reverse_roman("LXXVI") == 76, "76"
assert reverse_roman("CDXCIX") == 499, "499"
assert reverse_roman("MMMDCCCLXXXVIII") == 3888, "3888"
print("Great! It is time to Check your code!")
Feb. 2, 2021
Comments: