Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Using Enumeration - Explained solution in Clear category for Reverse Roman Numerals by Selindian
# Using an Enumaration class for translation
from enum import Enum
class ROM_TO_DEC(Enum):
I = 1
V = 5
X = 10
L = 50
C = 100
D = 500
M = 1000
def reverse_roman(roman_string):
prev_int, result = 0, 0 # Initialize variables
for letter in roman_string: # Loop over all roman chars
if prev_int == 0: # ... if previous in == 0 (first loop or in case lower followed by higher numer like IV)
prev_int = ROM_TO_DEC[letter].value # ... ... set previous = translated roman letter
else: # ... else
cur_int = ROM_TO_DEC[letter].value # ... ... set current = translated roman letter
if prev_int < cur_int: # ... if previous is smaller than current (example IV = 4)
result += cur_int - prev_int # ... ... add them to the result as second - first
prev_int = 0 # ... ... and set previous to 0
else: # ... else (normal order like VI = 6)
result += prev_int # ... ... just add previous
prev_int = cur_int # ... ... and let previous = current
result += prev_int # after the loop the last previous must be added
return result # return the 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!');
Sept. 10, 2022
Comments: