Created
February 23, 2021 23:51
-
-
Save dgnsrekt/9ae968fe24fb23b9b864f61a2cf08a02 to your computer and use it in GitHub Desktop.
This file contains 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
ROMAN_DICTIONARY = { | |
"I": 1, | |
"II": 2, | |
"III": 3, | |
"V": 5, | |
"X": 10, | |
"L": 50, | |
"C": 100, | |
"D": 500, | |
"M": 1000, | |
"IV": 4, | |
"IX": 9, | |
"XL": 40, | |
"XC": 90, | |
"CD": 400, | |
"CM": 900, | |
} | |
VALID_CHAR = [ | |
"II", | |
"III", | |
"IV", | |
"IX", | |
"XL", | |
"XC", | |
"CD", | |
"CM", | |
"I", | |
"V", | |
"X", | |
"L", | |
"C", | |
"D", | |
"M", | |
] | |
def roman_to_int(s: str) -> int: | |
assert len(s) >= 1, "too short" | |
assert len(s) <= 15, "too long" | |
for char in s: | |
assert char in VALID_CHAR, "Invalid Char" | |
parsed = [] | |
for valid in VALID_CHAR: | |
if valid in s: | |
parsed.append(valid) | |
s = s.replace(valid, "") | |
sum = 0 | |
for p in parsed: | |
sum += ROMAN_DICTIONARY[p] | |
print(sum) | |
return sum | |
assert roman_to_int("III") == 3 | |
assert roman_to_int("IV") == 4 | |
assert roman_to_int("IX") == 9 | |
assert roman_to_int("LVIII") == 58 | |
assert roman_to_int("MCMXCIV") == 1994 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment