Skip to content

Instantly share code, notes, and snippets.

@mahmoudhossam
Created February 19, 2018 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahmoudhossam/1c19d43ff067ff83ebca7f96c5a52a32 to your computer and use it in GitHub Desktop.
Save mahmoudhossam/1c19d43ff067ff83ebca7f96c5a52a32 to your computer and use it in GitHub Desktop.
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