mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-30 16:31:08 +00:00
c909da9b08
* pre-commit: Upgrade psf/black for stable style 2023 Updating https://github.com/psf/black ... updating 22.12.0 -> 23.1.0 for their `2023 stable style`. * https://github.com/psf/black/blob/main/CHANGES.md#2310 > This is the first [psf/black] release of 2023, and following our stability policy, it comes with a number of improvements to our stable style… Also, add https://github.com/tox-dev/pyproject-fmt and https://github.com/abravalheri/validate-pyproject to pre-commit. I only modified `.pre-commit-config.yaml` and all other files were modified by pre-commit.ci and psf/black. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
62 lines
1.7 KiB
Python
62 lines
1.7 KiB
Python
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"),
|
|
]
|
|
|
|
|
|
def roman_to_int(roman: str) -> int:
|
|
"""
|
|
LeetCode No. 13 Roman to Integer
|
|
Given a roman numeral, convert it to an integer.
|
|
Input is guaranteed to be within the range from 1 to 3999.
|
|
https://en.wikipedia.org/wiki/Roman_numerals
|
|
>>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999}
|
|
>>> all(roman_to_int(key) == value for key, value in tests.items())
|
|
True
|
|
"""
|
|
vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
|
|
total = 0
|
|
place = 0
|
|
while place < len(roman):
|
|
if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]):
|
|
total += vals[roman[place + 1]] - vals[roman[place]]
|
|
place += 2
|
|
else:
|
|
total += vals[roman[place]]
|
|
place += 1
|
|
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
|
|
"""
|
|
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
|
|
|
|
doctest.testmod()
|