fork download
  1. #!/usr/bin/env python3
  2.  
  3. from functools import reduce
  4. from operator import add, sub
  5.  
  6. def romanToInt(s):
  7. d = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
  8. def foo(y, x):
  9. n = d[x]
  10. val, prev = y
  11. return ((sub if prev > n else add)(val, n), n)
  12. return reduce(foo, reversed(s), (0, 0))[0]
  13.  
  14. if __name__ == '__main__':
  15. print(romanToInt('MC'))
  16. print(romanToInt('IV'))
  17. print(romanToInt('MCMLXVI'))
Success #stdin #stdout 0.04s 9908KB
stdin
Standard input is empty
stdout
1100
4
1966