80 lines
2.8 KiB
Python
Executable File
80 lines
2.8 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# romannum - convert to and from Roman numerals
|
|
# Usage: romannum NUMBER | romannum NUMERAL | romannum --range A B
|
|
# Numbers 1-3999. Input is auto-detected: digits -> Roman, letters -> Arabic.
|
|
# Example: romannum 2026 | romannum MMXXVI | romannum --range 1 10
|
|
import argparse, re, sys
|
|
|
|
PAIRS = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"),
|
|
(90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"),
|
|
(5, "V"), (4, "IV"), (1, "I")]
|
|
VAL = {r: v for v, r in PAIRS}
|
|
VALID = re.compile(r"^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$")
|
|
|
|
def to_roman(n):
|
|
if not 1 <= n <= 3999:
|
|
raise ValueError("number out of range 1-3999")
|
|
out = []
|
|
for v, r in PAIRS:
|
|
while n >= v:
|
|
out.append(r)
|
|
n -= v
|
|
return "".join(out)
|
|
|
|
def from_roman(s):
|
|
s = s.strip().upper()
|
|
if not s or not VALID.match(s):
|
|
raise ValueError(f"not a valid Roman numeral: {s!r}")
|
|
total, prev = 0, 0
|
|
for ch in reversed(s):
|
|
v = VAL[ch]
|
|
total = total - v if v < prev else total + v
|
|
prev = max(prev, v)
|
|
return total
|
|
|
|
def selftest():
|
|
assert to_roman(2026) == "MMXXVI" and from_roman("MMXXVI") == 2026
|
|
assert to_roman(4) == "IV" and to_roman(9) == "IX" and to_roman(3999) == "MMMCMXCIX"
|
|
assert from_roman("xiv") == 14 and from_roman("MCMXCIV") == 1994
|
|
for n in (1, 44, 99, 500, 1987, 3999):
|
|
assert from_roman(to_roman(n)) == n
|
|
try:
|
|
from_roman("IIII")
|
|
raise AssertionError("IIII accepted")
|
|
except ValueError:
|
|
pass
|
|
print("romannum selftest: ok (2026, subtractive pairs, round-trip, IIII rejected)")
|
|
return 0
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(prog="romannum",
|
|
description="Convert to and from Roman numerals (1-3999).")
|
|
p.add_argument("value", nargs="?", help="number (e.g. 2026) or numeral (e.g. MMXXVI)")
|
|
p.add_argument("--range", nargs=2, type=int, metavar=("A", "B"),
|
|
help="print a table for numbers A..B")
|
|
p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
|
|
a = p.parse_args()
|
|
if a.selftest:
|
|
return selftest()
|
|
if a.range:
|
|
lo, hi = a.range
|
|
if not 1 <= lo <= hi <= 3999:
|
|
print("romannum: range must be within 1-3999", file=sys.stderr); return 2
|
|
for n in range(lo, hi + 1):
|
|
print(f"{n:>4} {to_roman(n)}")
|
|
return 0
|
|
if not a.value:
|
|
p.error("VALUE is required (or use --range)")
|
|
v = a.value.strip()
|
|
try:
|
|
if v.isdigit():
|
|
print(to_roman(int(v)))
|
|
else:
|
|
print(from_roman(v))
|
|
except ValueError as e:
|
|
print(f"romannum: {e}", file=sys.stderr); return 2
|
|
return 0
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|