罗马到数字的转换程序 python

import re, itertools

def fromroman(RomanChar):
 Pattern = "^(M{0,3})(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$"
 CharList = list(re.search(Pattern, RomanChar).groups())
 return int(reduce(lambda X,Y: X + Y,
                map(mapNum, itertools.izip(CharList, [1000, 100, 10, 1]))))

def cmpfun(x, y):
 StrSeq = "IVXLCDM"
 if StrSeq.index(x) < StrSeq.index(y):
  return 1
 elif StrSeq.index(x) > StrSeq.index(y):
  return -1
 return 0

def mapNum((StrNum, Level)):
 if StrNum == "":
   return "0"
 Dict = {1   :{'I':1, 'V':5, 'X':10},
      10  :{'X':1, 'L':5, 'C':10},
      100 :{'C':1, 'D':5, 'M':10},
      1000:{'M':1}}
 CharDict = Dict[Level]
 MaxChr = sorted(StrNum, cmpfun)[0]
 AddList = map(lambda x: CharDict[x], list(StrNum[StrNum.index(MaxChr):]))
 DelList = map(lambda x: CharDict[x], list(StrNum[:StrNum.index(MaxChr)]))
 return str(sum(AddList) - sum(DelList))

你可能感兴趣的:(程序设计)