Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Simple roman numeral library
old_roman = (('M', 1000),
('D', 500),
('C', 100),
('L', 50),
('X', 10),
('V', 5),
('I', 1))
new_roman = (('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))
def to_roman(i, rules=new_roman):
'''What is the number i in Roman numerals?'''
result = ''
for roman, value in rules:
while i >= value:
result = result + roman
i = i - value
return result
def from_roman(r):
'''What is the Roman numeral r, converted back into a number?'''
result = 0
for roman, value in new_roman:
while r.startswith(roman):
r = r[len(roman):]
result = result + value
return result
olds = [to_roman(i, rules=old_roman) for i in range(1, 101)]
news = [to_roman(i) for i in range(1, 101)]
#for i in range(100):
# print '%3d %10s %4d %10s %4d' % (i+1, olds[i], from_roman(olds[i]),
# news[i], from_roman(news[i]))
def add_new_romans(r1, r2):
'''What is the sum of these new-style Roman numerals?
Note: achieved via conversion to arabic numbers.
'''
return to_roman(from_roman(r1) + from_roman(r2))
roman_dict = dict(old_roman)
roman_reductions = (('V', 'IIIII'),
('X', 'VV'),
('L', 'XXXXX'),
('C', 'LL'),
('D', 'CCCCC'),
('M', 'DD'))
def roman_sort(s):
'''Sort Roman digits into the proper order for "old" Roman numerals.'''
result = [i for i in s]
result.sort(lambda a, b: roman_dict[b] - roman_dict[a])
return ''.join(result)
def add_old_romans(r1, r2):
'''What is the sum of these old-style Roman numerals?
Note: achieved using reduction rules.
'''
result = roman_sort(r1 + r2)
for reduction, pattern in roman_reductions:
result = result.replace(pattern, reduction)
return result
i, j = 484, 414
k = i + j
print '%d + %d = %d' % (i, j, k)
a, b = to_roman(i), to_roman(j)
c = add_new_romans(a, b)
print '%s + %s = %s' % (a, b, c)
a, b = to_roman(i, rules=old_roman), to_roman(j, rules=old_roman)
c = add_old_romans(a, b)
print '%s + %s = %s' % (a, b, c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.