Skip to content

Instantly share code, notes, and snippets.

@seeni-dev
Last active August 10, 2019 10:53
Show Gist options
  • Save seeni-dev/928176960e86ce3f48413a5a9d05e41e to your computer and use it in GitHub Desktop.
Save seeni-dev/928176960e86ce3f48413a5a9d05e41e to your computer and use it in GitHub Desktop.
Daily Coding Problem 216 -> roman numeral to decimal
Given a number in Roman numeral format, convert it to decimal.
The values of Roman numerals are as follows:
{
'M': 1000,
'D': 500,
'C': 100,
'L': 50,
'X': 10,
'V': 5,
'I': 1
}
In addition, note that the Roman numeral system uses subtractive notation for numbers such as IV and XL.
For the input XIV, for instance, you should return 14.
================================================Solution.py======================================================
def isSubtractionEntity(a,b):
letters = ["I", "V", "X", "L", "C", "D", "M" ]
#get the index of b
b_i = -1
a_i = -1
for letter_i, letter in enumerate(letters):
if letter == b:
b_i = letter_i
if letter ==a:
a_i = letter_i
if a_i == -1 or b_i == -1:
raise Exception("letters doesn;t exist")
if a_i < b_i:
return True
return False
def getValue(letter):
values = {
"I":1,
"V":5,
"X":10,
"L":50,
"C":100,
"D":500,
"M":1000
}
return values[letter]
def convertToNumeral(roman):
romans = list(roman)
i = 0
num = 0
while i < len(romans)-1:
if isSubtractionEntity(romans[i],romans[i+1]):
num -= getValue(romans[i])
else:
num += getValue(romans[i])
i += 1
num += getValue(romans[-1])
return num
romans_list = ["I","II","IV","V","VI","IX","X","XI","XX","XXI","XXIV","XXV","XL","L","LX","LXXIII","XC","C"]
for roman in romans_list:
print("{}:{}".format(roman, convertToNumeral(roman)))
===================================================================================================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment