# 4 lines in Python

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

def romanToInt(self, s):
res, p = 0, 'I'
for c in s[::-1]:
res, p = res - d[c] if d[c] < d[p] else res + d[c], c
return res``````

• This post is deleted!

• Very concise!

• Smart solution

• Did something similar, but you can just iterate in order (and put the char -> int mapping in a list comp):

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

def romanToInt(self, s):
num, pre = 0, 1000
for i in [map[j] for j in s]:
num, pre = num + i - 2*pre if i > pre else num + i, i
return num``````

• excellent solution and very concise code! Thanks for ur share

• @Suralin said in 4 lines in Python:

Did something similar, but you can just iterate in order (and put the char -> int mapping in a list comp):

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

def romanToInt(self, s):
num, pre = 0, 1000
for i in [map[j] for j in s]:
num, pre = num + i - 2*pre if i > pre else num + i, i
return num``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.