# roman numeral converter using python

## Question:

I would like to ask if I should still continue this idea/way of roman numeral converter or should I think of a diff code.

Here is my current idea:

``````d_roman = { "I":1, "V": 5, "X":10}

rntconvert = raw_input("Enter Roman Num: " )

x = len(rntconvert)
if rntcovert is in dictionary

#print value of rntcovert

elif x==2

#add the value of two roman numbers except if first roman number is lower than the next then it will be subtracted
#(ex. IX, first char has lower value than next char, so it's like,  10 - 1)
``````

Is this doable? Thank you in advance.

edit: im using 2.7
explanation is: i separated the solving per amount of string returned

## Answers:

My solution to this:

``````class solution:
def roman_to_int(self, s):
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
int_val = 0
for i in range(len(s)):
if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]]
else:
int_val += rom_val[s[i]]
return int_val

print(solution().roman_to_int('MMMCMLXXXVI'))
print(solution().roman_to_int('MMMM'))
print(solution().roman_to_int('C'))

``````

Your idea is kind of correct, but to be frank it’s expressed poorly, and will only work with strings of at most two letters. In the future it might help to work on a better formulation before trying to implement an algorithm, but for the time being I can give you an example of how I did it:

``````def from_roman_to_arabic(n):
numerals={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
adjust_values={'IV':2,'IX':2,'XL':20,'XC':20,'CD':200,'CM':200}
s=0
for i in n:
s+=numerals[i]
for j in adjust_values:
if j in n:
s-=adjust_values[j]
return s
``````

my solution:

``````d={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}

str=input("Enter roman number : ").upper()
sum=0
i=0
while(i<len(str)):
if(i+1<len(str)):
if(d[str[i]]>=d[str[i+1]]):
sum+=d[str[i]]
i+=1
else:
sum+=(d[str[i+1]]-d[str[i]])
i+=2
else:
sum+=d[str[i]]
i+=1
print("Integer value =",sum)
``````
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.