Converting Roman Numerals to integers in python

前端 未结 17 1597
挽巷
挽巷 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:15

    Here's something i came up with using dictionary. It should be v.simple. Tell me what you think. I must say it does not handle the spoof roman numerals written in the form of MIM (instead of MCMXCIX for 1999). This is only for valid roman numerals.

    import re
    s = 0;
    a = dict();
    b = dict();
    r = "MMCMXCVIII"
    
    a['CM'] = 900;
    a['IX'] = 9;
    a ['IV'] = 4;
    a ['XL'] = 40;
    a ['CD'] = 400;
    a ['XC'] = 90;
    
    b['M'] = 1000;
    b['C'] = 100;
    b['D'] = 500;
    b['X'] = 10;
    b['V'] = 5;
    b['L'] = 50;
    b['I'] = 1;
    
    # Handle the tricky 4's and 9's first and remove them from the string
    
    for key in a:
            if key in r: 
                r = re.sub(key,'',r)
                s+=a[key];
    # Then straightforward multiplication of the not-so-tricky ones by their count.
    
    for key in b:
             s+= r.count(key) * b[key];
    
    print s; # This will print 2998
    

提交回复
热议问题