mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
add integer to roman function (#4050)
* add integer to roman function simply added fastest method i found. * Rename roman_to_integer.py to roman_numerals.py * Update roman_numerals.py * Update roman_numerals.py Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
parent
00f22a9970
commit
03889613bc
|
@ -21,6 +21,38 @@ def roman_to_int(roman: str) -> int:
|
|||
return total
|
||||
|
||||
|
||||
def int_to_roman(number: int) -> str:
|
||||
"""
|
||||
Given a integer, convert it to an roman numeral.
|
||||
https://en.wikipedia.org/wiki/Roman_numerals
|
||||
>>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999}
|
||||
>>> all(int_to_roman(value) == key for key, value in tests.items())
|
||||
True
|
||||
"""
|
||||
ROMAN = [
|
||||
(1000, "M"),
|
||||
(900, "CM"),
|
||||
(500, "D"),
|
||||
(400, "CD"),
|
||||
(100, "C"),
|
||||
(90, "XC"),
|
||||
(50, "L"),
|
||||
(40, "XL"),
|
||||
(10, "X"),
|
||||
(9, "IX"),
|
||||
(5, "V"),
|
||||
(4, "IV"),
|
||||
(1, "I"),
|
||||
]
|
||||
result = []
|
||||
for (arabic, roman) in ROMAN:
|
||||
(factor, number) = divmod(number, arabic)
|
||||
result.append(roman * factor)
|
||||
if number == 0:
|
||||
break
|
||||
return "".join(result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
Loading…
Reference in New Issue
Block a user