How to iterate through dictionary to match key value to string value

69 Views Asked by At

Im trying to solve roman numeral leetcode in python. here is my code

i tried multiple ways of comparing the dictionary to the key value and then each single character of the string to the dictionary but dont know how to put it in code.

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        LETTERS = {"I": 1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
        total = 0
        for key in LETTERS:
            if key == s[1:]:
                total += LETTERS[key]

        return total
1

There are 1 best solutions below

4
Roman Pavelka On

You don't want to iterate through your keys but through the string to get converted. First change your loop to something like:

for symbol in s:
     total += LETTERS[symbol]

However there is an issue with roman numbers like IV being 4 and IX being 9 with such approach.