Created
August 25, 2014 11:37
-
-
Save piontas/f9fbda14d8b4587e2262 to your computer and use it in GitHub Desktop.
Convert numbers in Roman numerals to
Arabic numerals.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
#!/usr/bin/env python | |
import sys | |
import os | |
m = { | |
'I': 1, | |
'V': 5, | |
'X': 10, | |
'L': 50, | |
'C': 100, | |
'D': 500, | |
'M': 1000 | |
} | |
def roman(r): | |
try: | |
r = int(r) | |
except ValueError: | |
r = str(r).replace(' ', '').upper() | |
if not set(m) >= set(r): | |
raise ValueError('Not a valid Roman numeral: %r' % r) | |
values = map(m.get, r) | |
value = sum(-n if n < max(values[i:]) else n | |
for i, n in enumerate(values)) | |
return value | |
raise ValueError('Not a valid Roman numeral: %r' % r) | |
def main(): | |
for i in sys.stdin: | |
sys.stdout.write('%d\n' % roman(i.strip(os.linesep))) | |
if __name__ == "__main__": | |
main() | |
### We can also use pip install rome==0.0.3 | |
# from rome import Roman | |
# for i in sys.stdin: | |
# sys.stdout.write('%d\n' % int(Roman(i.strip(os.linesep)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment