diff --git a/pqcli/lingo.py b/pqcli/lingo.py index 6731d6d..144a0ac 100644 --- a/pqcli/lingo.py +++ b/pqcli/lingo.py @@ -79,6 +79,43 @@ def to_roman(num: int) -> str: return ret +def to_arabic(roman: str) -> int: + num = 0 + rest = roman.upper() + + def _arab(ds: str, dn: int) -> bool: + nonlocal num, rest + if not rest.startswith(ds): + return False + rest = rest[len(ds) :] + num += dn + return True + + while _arab("T", 10000): + pass + _arab("MT", 9000) + _arab("A", 5000) + _arab("MA", 4000) + while _arab("M", 1000): + pass + _arab("CM", 900) + _arab("D", 500) + _arab("CD", 400) + while _arab("C", 100): + pass + _arab("XC", 90) + _arab("L", 50) + _arab("XL", 40) + while _arab("X", 10): + pass + _arab("IX", 9) + _arab("V", 5) + _arab("IV", 4) + while _arab("I", 1): + pass + return num + + def act_name(act: int) -> str: if act == 0: return "Prologue" diff --git a/tests/test_lingo.py b/tests/test_lingo.py index 584d6e5..5ca0562 100644 --- a/tests/test_lingo.py +++ b/tests/test_lingo.py @@ -1,4 +1,4 @@ -from pqcli.lingo import indefinite, to_roman +from pqcli.lingo import indefinite, to_arabic, to_roman def test_indefinite_article() -> None: @@ -19,3 +19,10 @@ def test_to_roman() -> None: assert to_roman(9000) == "MT" assert to_roman(14999) == "TMACMXCIX" assert to_roman(23456) == "TTMMMCDLVI" + + +def test_to_arabic_inverts_to_roman() -> None: + for num in [*range(1, 5000), 9000, 9999, 14999, 23456]: + assert to_arabic(to_roman(num)) == num + assert to_arabic("N") == 0 + assert to_arabic("iv") == 4