python-checkio/ElectronicStation/reverse-roman-numerals.py

72 lines
3.0 KiB
Python
Raw Normal View History

2020-01-02 17:30:27 +01:00
def reverse_roman(roman_string):
mille = ['', 'M', 'MM', 'MMM']
centaine = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']
dixaine = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']
unite = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']
number = 0
roman_string_length = len(roman_string)
index = 0
while True:
letter = roman_string[index]
current_number = letter
is_multiple = False
if current_number in mille:
while current_number in mille and index < roman_string_length - 1:
index += 1
current_number += roman_string[index]
if current_number not in mille:
is_multiple = True
current_number = current_number[0:-1]
number += (mille.index(current_number) * 1000)
elif current_number in centaine:
while current_number in centaine and index < roman_string_length - 1:
index += 1
current_number += roman_string[index]
if current_number not in centaine:
is_multiple = True
current_number = current_number[0:-1]
number += 100 * (centaine.index(current_number))
elif current_number in dixaine:
while current_number in dixaine and index < roman_string_length - 1:
index += 1
current_number += roman_string[index]
if current_number not in dixaine:
is_multiple = True
current_number = current_number[0:-1]
number += 10 * (dixaine.index(current_number))
elif current_number in unite:
while current_number in unite and index < roman_string_length - 1:
index += 1
current_number += roman_string[index]
if current_number not in unite:
is_multiple = True
current_number = current_number[0:-1]
number += unite.index(current_number)
if index == roman_string_length - 1:
if is_multiple:
letter = roman_string[index]
if letter in mille:
number += (mille.index(letter)) * 1000
elif letter in centaine:
number += 100 * (centaine.index(letter))
elif letter in dixaine:
number += 10 * (dixaine.index(letter))
elif letter in unite:
number += unite.index(letter)
break
return number
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'
assert reverse_roman("I") == 1, '1'
assert reverse_roman("X") == 10, '10'
assert reverse_roman("MMMDCCCX") == 3810, '3810'
print('Great! It is time to Check your code!')