Roman Numerals
16 February 2025
A solution to convert Arabic numbers to Roman Numerals.
Solution
""" to_roman.py """
# usage: python3 to_roman.py 1979
import sys
def roman(value):
""" value as a roman numeral """
subs = [('IIII', 'IV'), ('IVI', 'V'), ('VIV', 'IX'), ('IXI', 'X'),
('XXXX', 'XL'), ('XLX', 'L'), ('LXL', 'XC'), ('XCX', 'C'),
('CCCC', 'CD'), ('CDC', 'D'), ('DCD', 'CM'), ('CMC', 'M')]
output = ''
i = value
while i > 0:
output += 'I'
for x, y in subs:
if output.endswith(x):
output = output[:-len(x)] + y
i -= 1
return output
if __name__ == '__main__':
num = int(sys.argv[1])
print(roman(num))
A solution to convert Roman numerals to an Arabic Number.
Solution
""" from_roman.py """
# usage: python3 from_roman.py MCMLXXIX
import sys
def arabic(value):
""" value as an arabic numeral """
subs = {'$': 0, 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'M': 1000}
output = 0
v = value + '$'
for i, c in enumerate(v[:-1]):
sign = -1 if subs[c] < subs[v[i + 1]] else 1
output += sign * subs[c]
return output
if __name__ == '__main__':
num = sys.argv[1]
print(arabic(num))