Skip to content

Instantly share code, notes, and snippets.

@piontas
Last active August 29, 2015 14:01
Show Gist options
  • Save piontas/538d4dcfe44a7a22a78a to your computer and use it in GitHub Desktop.
Save piontas/538d4dcfe44a7a22a78a to your computer and use it in GitHub Desktop.
#!/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))))
Please write a program for converting numbers written in Roman numerals to
Arabic numerals. The program will get Roman numerals on standard input,
separated by a new line character. It should print respective Arabic numerals
separated by a new line to standard output.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment