public
Last active

Simple roman numeral library

  • Download Gist
roman.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.