Created
December 7, 2018 15:11
-
-
Save ReeceHub/814ea85d4f15c0ce8d4bd79156f99983 to your computer and use it in GitHub Desktop.
roman numerals tdd fridays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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