Created
February 19, 2018 22:45
-
-
Save mahmoudhossam/1c19d43ff067ff83ebca7f96c5a52a32 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def roman_numeral_to_int(string): | |
symbols = { | |
'I': 1, | |
'V': 5, | |
'X': 10, | |
'L': 50, | |
'C': 100, | |
'D': 500, | |
'M': 1000 | |
} | |
repetitions = {} | |
result = 0 | |
skip = 0 | |
for i, c in enumerate(string): | |
if i == skip and i != 0: | |
continue | |
if c not in symbols: | |
return None | |
if c in repetitions.items(): | |
repetitions[c] += 1 | |
else: | |
repetitions = {c: 1} | |
for r, v in repetitions.items(): | |
if (r in ['L', 'D', 'V'] and v > 1) or (r in ['I', 'X', 'C'] and v > 3): | |
return None | |
if c == 'I': | |
# last character in the string | |
if i == len(string) - 1: | |
result += 1 | |
elif string[i+1] == 'V': | |
result += 4 | |
skip = i + 1 | |
elif string[i+1] == 'X': | |
result += 9 | |
skip = i + 1 | |
elif c == 'X': | |
# last character in the string | |
if i == len(string) - 1: | |
result += 10 | |
elif string[i+1] == 'L': | |
result += 40 | |
skip = i + 1 | |
elif string[i+1] == 'C': | |
result += 90 | |
skip = i + 1 | |
elif c == 'C': | |
# last character in the string | |
if i == len(string) - 1: | |
result += 100 | |
elif string[i+1] == 'D': | |
result += 400 | |
skip = i + 1 | |
elif string[i+1] == 'M': | |
result += 900 | |
skip = i + 1 | |
else: | |
skip = 0 | |
result += symbols[c] | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment