Skip to content

Instantly share code, notes, and snippets.

@codecakes
Created May 9, 2023 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codecakes/9b5f89319fd54ea7ffa0aa68b2a3f443 to your computer and use it in GitHub Desktop.
Save codecakes/9b5f89319fd54ea7ffa0aa68b2a3f443 to your computer and use it in GitHub Desktop.
Integer conversion to roman literal
import math
# ================ Int to Roman ==================== #
RomanMapping = {
1: 'I',
4: 'IV',
5: 'V',
9: 'IX',
10: 'X',
40: 'XL',
50: 'L',
90: 'XC',
100: 'C',
400: 'CD',
500: 'D',
900: 'CM',
1000: 'M'
}
def int_to_roman(number: int) -> str:
roman_number = ""
for num_key, roman_literal in sorted(RomanMapping.items(), reverse=True, key=lambda x: x[0]):
while number >= num_key:
number -= num_key
roman_number += roman_literal
return roman_number
assert int_to_roman(1) == 'I'
assert int_to_roman(4) == 'IV'
assert int_to_roman(5) == 'V'
assert int_to_roman(9) == 'IX'
assert int_to_roman(10) == 'X'
assert int_to_roman(40) == 'XL'
assert int_to_roman(100) == 'C'
assert int_to_roman(400) == 'CD'
assert int_to_roman(500) == 'D'
assert int_to_roman(25) == 'XXV'
assert int_to_roman(26) == 'XXVI'
assert int_to_roman(27) == 'XXVII'
def countX_from_range(start: int, end: int) -> int:
return sum(
(int_to_roman(num)).count("X") for num in range(start, end + 1)
)
assert countX_from_range(1, 10) == 2
assert (countX_from_range(1, 14)) == 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment