Aug-14-2020, 03:21 PM
I am trying to convert the given roman numerals to just numerals, with the following logic :
Here,
M - 1000, C-100, X-10, V-5, I-1
example :
R_num- MCMXCVI
index- 1234567
logic - 1000 + (1000-100) + (100-10) + 5 + 6
index- 1 + (3-2) + (5-4) + 6 + 7
Here i am searching next value from the current value subtracting it if its not greater we are adding it normally.
Having hard time to think properly in python. Please help.
Here,
M - 1000, C-100, X-10, V-5, I-1
example :
R_num- MCMXCVI
index- 1234567
logic - 1000 + (1000-100) + (100-10) + 5 + 6
index- 1 + (3-2) + (5-4) + 6 + 7
Here i am searching next value from the current value subtracting it if its not greater we are adding it normally.
Having hard time to think properly in python. Please help.
def roman_numeral(num): """ Write a Python class to convert an roman numeral to a integer. Logic: https://www.rapidtables.com/convert/number/how-roman-numerals-to-number.html """ # Input the string # Map of roman numerals and the corresponding values in a dictionary. NUMERALS = {1000:'M', 900:'CM', 500:'D', 400:'CD', 100:'C', 90:'XC', 50:'L', 40:'XL', 10:'X', 9:'IX', 5:'V', 4:'IV', 1:'I'} retval=[] #Check if each char matches with the dictionary and take the numerical value of the inputed roman for k in range(len(num)): for i,j in NUMERALS.items(): if(j==num[k]): retval.append(i) elm_count = len(retval) result=0 result_less=0 result_more=0 ind_tracker=0 #Check if next char from the position of current char if that numerical value is greater then current numerical value. #If it is greater subtract the current numeric value, if not greater then add it. for ind,i in enumerate(retval): print('ind= ',ind,'i= ', i) #Using this below condition to skip if we have already subtracted the current value from previous value. if( ind_tracker>ind): continue if((ind+1 < elm_count)): if(i<retval[ind+1]): #print('result=',result,'retval[ind]=',retval[ind],'retval[ind+1]=', retval[ind+1]) result_less=retval[ind+1]-retval[ind] print('result_less=',result_less) ind_tracker=ind+1 else: result_more+=retval[ind]+result_less print('result_more=',result_more) result=result_more print('final result= ',result) return result roman_numeral('MCMXCVI')