Generates a string of roman numerals for a given integer. e.g. >>> generate_roman_numerals(89) 'LXXXIX' >>> generate_roman_numerals(4) 'IV'
(num: int)
| 60 | |
| 61 | |
| 62 | def generate_roman_numerals(num: int) -> str: |
| 63 | """ |
| 64 | Generates a string of roman numerals for a given integer. |
| 65 | e.g. |
| 66 | >>> generate_roman_numerals(89) |
| 67 | 'LXXXIX' |
| 68 | >>> generate_roman_numerals(4) |
| 69 | 'IV' |
| 70 | """ |
| 71 | |
| 72 | numerals = "" |
| 73 | |
| 74 | m_count = num // 1000 |
| 75 | numerals += m_count * "M" |
| 76 | num %= 1000 |
| 77 | |
| 78 | c_count = num // 100 |
| 79 | if c_count == 9: |
| 80 | numerals += "CM" |
| 81 | c_count -= 9 |
| 82 | elif c_count == 4: |
| 83 | numerals += "CD" |
| 84 | c_count -= 4 |
| 85 | if c_count >= 5: |
| 86 | numerals += "D" |
| 87 | c_count -= 5 |
| 88 | numerals += c_count * "C" |
| 89 | num %= 100 |
| 90 | |
| 91 | x_count = num // 10 |
| 92 | if x_count == 9: |
| 93 | numerals += "XC" |
| 94 | x_count -= 9 |
| 95 | elif x_count == 4: |
| 96 | numerals += "XL" |
| 97 | x_count -= 4 |
| 98 | if x_count >= 5: |
| 99 | numerals += "L" |
| 100 | x_count -= 5 |
| 101 | numerals += x_count * "X" |
| 102 | num %= 10 |
| 103 | |
| 104 | if num == 9: |
| 105 | numerals += "IX" |
| 106 | num -= 9 |
| 107 | elif num == 4: |
| 108 | numerals += "IV" |
| 109 | num -= 4 |
| 110 | if num >= 5: |
| 111 | numerals += "V" |
| 112 | num -= 5 |
| 113 | numerals += num * "I" |
| 114 | |
| 115 | return numerals |
| 116 | |
| 117 | |
| 118 | def solution(roman_numerals_filename: str = "/p089_roman.txt") -> int: |