Skip to content

Commit 0388961

Browse files
Ksenginecclauss
andauthored
add integer to roman function (TheAlgorithms#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 <[email protected]>
1 parent 00f22a9 commit 0388961

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

conversions/roman_to_integer.py renamed to conversions/roman_numerals.py

+32
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,38 @@ def roman_to_int(roman: str) -> int:
2121
return total
2222

2323

24+
def int_to_roman(number: int) -> str:
25+
"""
26+
Given a integer, convert it to an roman numeral.
27+
https://en.wikipedia.org/wiki/Roman_numerals
28+
>>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999}
29+
>>> all(int_to_roman(value) == key for key, value in tests.items())
30+
True
31+
"""
32+
ROMAN = [
33+
(1000, "M"),
34+
(900, "CM"),
35+
(500, "D"),
36+
(400, "CD"),
37+
(100, "C"),
38+
(90, "XC"),
39+
(50, "L"),
40+
(40, "XL"),
41+
(10, "X"),
42+
(9, "IX"),
43+
(5, "V"),
44+
(4, "IV"),
45+
(1, "I"),
46+
]
47+
result = []
48+
for (arabic, roman) in ROMAN:
49+
(factor, number) = divmod(number, arabic)
50+
result.append(roman * factor)
51+
if number == 0:
52+
break
53+
return "".join(result)
54+
55+
2456
if __name__ == "__main__":
2557
import doctest
2658

0 commit comments

Comments
 (0)