#!/usr/bin/env python3
from functools import reduce
from operator import add, sub
def romanToInt(s):
d = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
def foo(y, x):
n = d[x]
val, prev = y
return ((sub if prev > n else add)(val, n), n)
return reduce(foo, reversed(s), (0, 0))[0]
if __name__ == '__main__':
print(romanToInt('MC'))
print(romanToInt('IV'))
print(romanToInt('MCMLXVI'))
IyEvdXNyL2Jpbi9lbnYgcHl0aG9uMwoKZnJvbSBmdW5jdG9vbHMgaW1wb3J0IHJlZHVjZQpmcm9tIG9wZXJhdG9yIGltcG9ydCBhZGQsIHN1YgoKZGVmIHJvbWFuVG9JbnQocyk6CiAgICBkID0geydJJzogMSwgJ1YnOiA1LCAnWCc6IDEwLCAnTCc6IDUwLCAnQyc6IDEwMCwgJ0QnOiA1MDAsICdNJzogMTAwMH0KICAgIGRlZiBmb28oeSwgeCk6CiAgICAgICAgbiA9IGRbeF0KICAgICAgICB2YWwsIHByZXYgPSB5CiAgICAgICAgcmV0dXJuICgoc3ViIGlmIHByZXYgPiBuIGVsc2UgYWRkKSh2YWwsIG4pLCBuKQogICAgcmV0dXJuIHJlZHVjZShmb28sIHJldmVyc2VkKHMpLCAoMCwgMCkpWzBdCgppZiBfX25hbWVfXyA9PSAnX19tYWluX18nOgogICAgcHJpbnQocm9tYW5Ub0ludCgnTUMnKSkKICAgIHByaW50KHJvbWFuVG9JbnQoJ0lWJykpCiAgICBwcmludChyb21hblRvSW50KCdNQ01MWFZJJykp