Skip to content

Instantly share code, notes, and snippets.

@ReeceHub
Created December 7, 2018 15:11
Show Gist options
  • Save ReeceHub/814ea85d4f15c0ce8d4bd79156f99983 to your computer and use it in GitHub Desktop.
Save ReeceHub/814ea85d4f15c0ce8d4bd79156f99983 to your computer and use it in GitHub Desktop.
roman numerals tdd fridays
order = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
equivalences = {
'IIIII': 'V',
'VV': 'X',
'XXXXX': 'L',
'LL': 'C',
'CCCCC': 'D',
'DD': 'M',
}
short_forms = {
'IIII': 'IV',
'VIIII': 'IX',
'XXXX': 'XL',
'LXXXX': 'XC',
'DCCCC': 'CM',
}
def short_to_long(numeral):
for long, short in short_forms.items():
numeral = numeral.replace(short, long)
return numeral
def long_to_short(numeral):
for long, short in reversed(list(short_forms.items())):
numeral = numeral.replace(long, short)
return numeral
def add(first, second):
first = short_to_long(first)
second = short_to_long(second)
result = ''.join(sorted(
first + second,
key=lambda x: order.index(x),
reverse=True
))
for long, short in equivalences.items():
result = result.replace(long, short)
return long_to_short(result)
from roman_numerals import add
import pytest
@pytest.mark.parametrize('first,second,expected', [
('I', 'I', 'II'),
('I', 'II', 'III'),
('II', 'III', 'V'),
('V', 'I', 'VI'),
('I', 'V', 'VI'),
('V', 'V', 'X'),
('VII', 'III', 'X'),
('III', 'VII', 'X'),
('XXVII', 'III', 'XXX'),
('XXX', 'XX', 'L'),
('XXXV', 'XV', 'L'),
('XV', 'XXXV', 'L'),
('L', 'L', 'C'),
('LXXX', 'XX', 'C'),
('XX', 'LXXX', 'C'),
('C', 'I', 'CI'),
('L', 'I', 'LI'),
('L', 'X', 'LX'),
('X', 'I', 'XI'),
('X', 'V', 'XV'),
('CCC', 'CC', 'D'),
('D', 'D', 'M'),
('M', 'D', 'MD'),
])
def test_non_backwards_ones(first, second, expected):
assert add(first, second) == expected
@pytest.mark.parametrize('first,second,expected', [
('IV', 'I', 'V'),
('I', 'IV', 'V'),
('IV', 'IV', 'VIII'),
('XIV', 'I', 'XV'),
('IX', 'I', 'X'),
('I', 'IX', 'X'),
('XL', 'X', 'L'),
('X', 'XL', 'L'),
('II', 'II', 'IV'),
('XX', 'XX', 'XL'),
('VIII', 'I', 'IX'),
('LXXX', 'X', 'XC'),
('XLIV', 'I', 'XLV'),
('IX', 'I', 'X'),
('MDCCCXCV', 'CIV', 'MCMXCIX')
])
def test_backwards_ones(first, second, expected):
assert add(first, second) == expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment