Created
August 11, 2018 18:15
-
-
Save rpgraham84/a6734d451b49a454bcd8bb9fc34def24 to your computer and use it in GitHub Desktop.
Convert integers to roman and vice-versa
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
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