from functools import reduce dct_n2r = {0: '', 1:'I', 2:'II', 3:'III', 4:'IV', 5:'V', 6:'VI', 7:'VII', 8:'VIII', 9:'IX', 10:'X', 20:'XX', 30:'XXX', 40:'XL', 50:'L', 60:'LX', 70:'LXX', 80:'LXXX', 90:'XC', 100:'C', 200:'CC', 300:'CCC', 400:'CD', 500:'D', 600:'DC', 700:'DCC', 800:'DCCC', 900:'CM', 1000:'M'} dct_r2n = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} def r2n(r_num): last = 0 tale = 0 for digit in reversed(list(map(lambda x: dct_r2n[x], r_num))): if digit < last: tale -= digit else: tale += digit last = digit return tale def n2r(num): tale = dct_n2r[1000] * (num // 1000) num %= 1000 tale += dct_n2r[num - num % 100] num %= 100 tale += dct_n2r[num - num % 10] num %= 10 return tale + dct_n2r[num] def get_file(fn): with open(fn, 'r') as f: return list(map(lambda x: x.strip(), f.readlines())) def item_len(lst): return reduce(lambda x, y: x + len(y), lst, 0) def trans(fn): lst = get_file(fn) return item_len(lst) - item_len(map(lambda x: n2r(r2n(x)), lst)) print(trans('../resource/roman.txt'))