[Python:Accepted] Leetcode: Roman to Integer

Leetcode: Roman to Integer

 

import unittest

# refs: http://en.wikipedia.org/wiki/Roman_numerals
class Solution:

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

    # @return an integer
    def romanToInt(self, s):
        index = -1
        num_list = []
        for c in s:
            current_value = Solution.ROMAN_TO_INT.get(c)
            if index == -1:
                num_list.append(current_value)
            else:
                if num_list[index] < current_value:
                    num_list[index] = num_list[index] * -1
                num_list.append(current_value)
            index += 1

        return sum(num_list)

class TestSolution(unittest.TestCase):

    def test_basic_mapping(self):
        s = Solution()
        self.assertEqual(s.romanToInt('I'), 1)
        self.assertEqual(s.romanToInt('IV'), 4)
        self.assertEqual(s.romanToInt('V'), 5)
        self.assertEqual(s.romanToInt('IX'), 9)
        self.assertEqual(s.romanToInt('X'), 10)
        self.assertEqual(s.romanToInt('XL'), 40)
        self.assertEqual(s.romanToInt('L'), 50)
        self.assertEqual(s.romanToInt('XC'), 90)
        self.assertEqual(s.romanToInt('C'), 100)
        self.assertEqual(s.romanToInt('CD'), 400)
        self.assertEqual(s.romanToInt('D'), 500)
        self.assertEqual(s.romanToInt('CM'), 900)
        self.assertEqual(s.romanToInt('M'), 1000)

    def test_romanToInt(self):
        s = Solution()
        self.assertEqual(s.romanToInt('MLXVI'), 1066)
        self.assertEqual(s.romanToInt('II'), 2)
        self.assertEqual(s.romanToInt('XIII'), 13)
        self.assertEqual(s.romanToInt('CCVII'), 207)
        self.assertEqual(s.romanToInt('MMXIV'), 2014)
        self.assertEqual(s.romanToInt('MCMLIV'), 1954)
        self.assertEqual(s.romanToInt('MCMXC'), 1990)

if __name__ == '__main__':
    unittest.main()

Leave a Reply