Roman to integer conversion

Viewed 66

Hi I'm trying to do a Roman to integer leetcode problem, I did everything I assigned a value to everything and with a map function and I get the exact letter, the input is like this

Input: s = "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3.

the problem is I get the letters as a string like ['L']['V']['I']['I']['I'] How can I make the "L" as a string to be The variable that is assigned a value of 50

I = 1
V = 5
X = 10
L = 50
C = 100
D = 500
M = 1000
s = "LVIII"
length = len(s)
numbers = list(map(list, s))
x = 0
while x < length:
    print(numbers[x])
    x = x + 1
4 Answers

make dictionary mapping

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

s = list("LVIII")
sum = 0
for x in s :
    sum+= dict_[x]
#op
58

When you wan to access a variable based on a runtime input from a user, you almost certainly want to use a data structure designed to map a string to a value. In Python this means you want a dictionary, or some variant thereon.

Then we just need to map over the input string, using each character tto get its associated value, and then sum those.

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

s = "LVIII"
v = sum(rom_num_values.get(ch, 0) for ch in s)
# 58

Note: Doesn't handle roman numerals like IV.

Based on answer of qaiser I recommend to additionally check if there is, e.g., a 'I' before a 'V'. In this case the 'I' must be subtracted from 'V', i.e., 5-1=4.

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

s = list("LVIII")    
res = 0
i = 0
while i < len(s):        
    if s[i] == 'I' and i < len(s)-1:
        if s[i+1] != 'I':
            res += dict_[s[i+1]] - dict_[s[i]]
            i += 2    
            continue
    res += dict_[s[i]]
    i += 1
print(res)

# output = 58

and with input s = list("LIV")

# output = 54

I'm sure there is a more concise/pythonic way, but for the first attempt...

class Solution:
def romanToInt(self, s: str) -> int:
    mapping = {
        "I": 1,
        "V": 5,
        "X": 10,
        "L": 50,
        "C": 100,
        "D": 500,
        "M": 1000
    }
    result = 0
    for i in range(len(s)):
        result += mapping[s[i]]
        if i > 0 and mapping[s[i]] > mapping[s[i - 1]]:
            result -= 2 * mapping[s[i - 1]]

    return result
Related