Last active
September 14, 2021 15:39
-
-
Save chbndrhnns/c419b779c89e3870ccfd0a58f8d42144 to your computer and use it in GitHub Desktop.
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
import pytest | |
BASE = 10 | |
SYMBOLS_DICT = {1: "I", 5: "V", 10: "X", 50: "L", 100: "C", 500: "D", 1000: "M"} | |
def get_digit_at(num, pos): | |
return num // 10 ** pos % 10 | |
def get_symbols_for(pos): | |
return ( | |
SYMBOLS_DICT.get(pos), | |
SYMBOLS_DICT.get(pos * 5), | |
SYMBOLS_DICT.get(pos * 10, "") | |
) | |
def convert_to_roman(arabic): | |
exponent = len(str(arabic)) | |
result = "" | |
while exponent >= 0: | |
digit = get_digit_at(arabic, exponent) | |
position = BASE ** exponent | |
current, next_five, next_ten = get_symbols_for(position) | |
if 0 < digit < 4: | |
result += current * digit | |
elif digit == 4: | |
result += current + next_five | |
elif digit == 5: | |
result += next_five | |
elif 5 < digit < 9: | |
result += next_five + (current * (digit - 5)) | |
elif digit == 9: | |
result += current + next_ten | |
exponent -= 1 | |
return result | |
@pytest.mark.parametrize( | |
"arabic, roman", [ | |
(1, "I"), | |
(2, "II"), | |
(3, "III"), | |
(4, "IV"), | |
(5, "V"), | |
(6, "VI"), | |
(7, "VII"), | |
(8, "VIII"), | |
(9, "IX"), | |
] | |
) | |
def test_one_digits(arabic, roman): | |
assert convert_to_roman(arabic) == roman | |
@pytest.mark.parametrize( | |
"arabic, roman", [ | |
(10, "X"), | |
(20, "XX"), | |
(30, "XXX"), | |
(40, "XL"), | |
(50, "L"), | |
(60, "LX"), | |
(70, "LXX"), | |
(80, "LXXX"), | |
(90, "XC"), | |
] | |
) | |
def test_two_digits__ones_zero(arabic, roman): | |
assert convert_to_roman(arabic) == roman | |
@pytest.mark.parametrize( | |
"arabic, roman", [ | |
(100, "C"), | |
(200, "CC"), | |
(300, "CCC"), | |
(400, "CD"), | |
(500, "D"), | |
(600, "DC"), | |
(700, "DCC"), | |
(800, "DCCC"), | |
(900, "CM"), | |
] | |
) | |
def test_three_digits__ones_and_tens_zero(arabic, roman): | |
assert convert_to_roman(arabic) == roman | |
@pytest.mark.parametrize( | |
"arabic, roman", [ | |
(11, "XI"), | |
(99, "XCIX"), | |
(999, "CMXCIX"), | |
] | |
) | |
def test_other_examples(arabic, roman): | |
assert convert_to_roman(arabic) == roman |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment