2 Lines in Python [Dictionary] [List Comprehension]

  • 0
    v = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
    return sum([v[s[i]] if v[s[i]] >= v[s[i+1]] else -v[s[i]] for i in range(len(s)-1)])+v[s[-1]]

    If a letter's value is less than that of the next (e.g. IV, IX, XL, LC, CD, CM, etc.), then its value will be subtracted. Otherwise, the value added.

Log in to reply

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