Converting Roman Numerals to integers in python

前端 未结 17 1599
挽巷
挽巷 2020-12-03 03:56

This is now my current code after what user2486 said.

def romanMap():
    map=((\"M\",  1000),(\"CM\", 900),(\"D\",  500),(\"CD\", 400),(\"C\",  100),(\"XC\"         


        
17条回答
  •  情深已故
    2020-12-03 04:23

    Roman numerals are read from left to right, as you add or subtract the value of each symbol.

    If a value is lower than the following value, it will be subtracted. Otherwise it will be added.

    For example, we want to conver the Roman numeral MCMLIV to an Arabic number:

    M = 1000 must be added, because the following letter C =100 is lower.
    C = 100 must be subtracted because the following letter M =1000 is greater.
    M = 1000 must be added, because the following letter L = 50 is lower.
    L = 50 must be added, because the following letter I =1 is lower.
    I = 1 must be subtracted, because the following letter V = 5 is greater.
    V = 5 must be added, because there are no more symbols left.
    

    We can now calculate the number:

    1000 - 100 + 1000 + 50 - 1 + 5 = 1954 
    

    ref : http://www.mathinary.com/roman_numerals_from_roman_numerals_to_arabic_numbers.jsp

    def from_roman(num):
        roman_numerals = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        result = 0
        for i,c in enumerate(num):
            if (i+1) == len(num) or roman_numerals[c] >= roman_numerals[num[i+1]]:
                result += roman_numerals[c]
            else:
                result -= roman_numerals[c]
        return result
    

提交回复
热议问题