Skip to content

Instantly share code, notes, and snippets.

@rpgraham84
Created August 11, 2018 18:15
Show Gist options
  • Save rpgraham84/a6734d451b49a454bcd8bb9fc34def24 to your computer and use it in GitHub Desktop.
Save rpgraham84/a6734d451b49a454bcd8bb9fc34def24 to your computer and use it in GitHub Desktop.
Convert integers to roman and vice-versa
import re
numerals = {"M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100,
"XC": 90, "L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5,
"IV": 4, "I": 1}
r = re.compile('|'.join(sorted(numerals.keys(), key=len, reverse=True)))
def to_roman(n, s=''):
for num, val in numerals.items():
if n // val:
n -= val
s += num
return to_roman(n, s)
if not n:
return s
def to_int(s):
tokens = r.findall(s)
return sum(numerals[t] for t in tokens)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment