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:
Kavindu Santhusa 2020-12-21 13:55:59 -08:00 committed by GitHub
parent 00f22a9970
commit 03889613bc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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