Skip to content

Instantly share code, notes, and snippets.

@paul-schwendenman
Created February 23, 2015 04:47
Show Gist options
  • Save paul-schwendenman/f08bfb2a88ba61cb22aa to your computer and use it in GitHub Desktop.
Save paul-schwendenman/f08bfb2a88ba61cb22aa to your computer and use it in GitHub Desktop.
Roman Numerals
order = 'MDCLXVI'
add_to_sub = (
('VIIII', 'IX'),
('LXXXX', 'XC'),
('DCCCC', 'CM'),
('IIII', 'IV'),
('XXXX', 'XL'),
('CCCC', 'CD'),
)
sub_to_add = (
('IX', 'VIIII'),
('IV', 'IIII'),
('XC', 'LXXXX'),
('XL', 'XXXX'),
('CM', 'DCCCC'),
('CD', 'CCCC'),
)
pairs = (
('IIIII', 'V'),
('VV', 'X'),
('XXXXX', 'L'),
('LL', 'C'),
('CCCCC', 'D'),
('DD', 'M'),
)
roman_value = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
def sort_roman(input):
return ''.join(sorted(input, key=order.index))
def replace_roman(input, replace):
for key, value in replace:
input = input.replace(key, value)
return input
def add_roman(number_one, number_two, debug=False):
number_one = replace_roman(number_one, sub_to_add)
number_two = replace_roman(number_two, sub_to_add)
result = number_one + number_two
result = sort_roman(result)
if debug:
print result, convert_from_roman(result)
result = replace_roman(result, pairs)
if debug:
print result, convert_from_roman(result)
result = replace_roman(result, add_to_sub)
return result
def convert_to_roman(input):
result = 'I' * input
result = replace_roman(result, pairs)
result = replace_roman(result, add_to_sub)
return result
def convert_from_roman(input):
input = replace_roman(input, sub_to_add)
value = 0
for char in input:
value += roman_value[char]
return value
def test(i, j):
try:
for a in range(1, i + 1):
for b in range(1, j + 1):
a_r = convert_to_roman(a)
b_r = convert_to_roman(b)
c_r = add_roman(a_r, b_r)
c = convert_from_roman(c_r)
assert a + b == c
except AssertionError:
print "%d + %d = %d, %s + %s = %s" % (a, b, c, a_r, b_r, c_r)
if __name__ == '__main__':
#result = add_roman("MDXIV", "MMXIV")
#print result, convert_from_roman(result)
a = 'CD'
b = 'M'
result = add_roman(a, b, debug=True)
print result, convert_from_roman(result)
test(2000, 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment