Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from math import floor
- def romanize_digit(digit: int, place: str):
- """
- Place should take either 'I', 'X', 'C', or 'M'
- """
- index = ["I","X","C","M"]
- fives = {
- "I": "V",
- "X":"L",
- "C":"D",
- "M": "MMMMM"
- }
- if digit == 9:
- next_place = index[index.index(place)+1]
- return place+next_place if place != 'M' else 'M'*9
- elif digit > 5:
- return fives[place]+place*(digit % 5)
- elif digit == 4:
- return place+fives[place]
- else:
- return place*digit
- def roman_numeral(num: int) -> str:
- """
- Let's approach this digit by digit. So we can turn the int into a list of chars:
- 238 --> ['2','3','8']
- """
- roman_numerals = ''
- digits = [int(c) for c in str(num)]
- index = ["I","X","C","M"]
- for i in range(min(len(digits), 4 if num < 10000 else 3)):
- place = index[i]
- roman_numerals = romanize_digit(digits[-i-1], place) + roman_numerals
- if num > 10000:
- roman_numerals = 'M'*(floor(num/1000)) + roman_numerals
- return roman_numerals
- def test_roman_numeral():
- assert roman_numeral(3) == "III"
- assert roman_numeral(7) == "VII"
- assert roman_numeral(9) == "IX"
- assert roman_numeral(12) == "XII"
- assert roman_numeral(238) == "CCXXXVIII"
- assert roman_numeral(6000) == "MMMMMM"
- assert roman_numeral(11001) == "MMMMMMMMMMMI"
- assert roman_numeral(19011) == "MMMMMMMMMMMMMMMMMMMXI"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement