mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-07-24 16:55:45 +08:00
Create roman_to_integer.py (#1636)
* added roman to integer conversion (LeetCode No. 13) * updated directory to include Roman to Integer * Delete DIRECTORY.md * Update roman_to_integer.py Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
27
conversions/roman_to_integer.py
Normal file
27
conversions/roman_to_integer.py
Normal file
@ -0,0 +1,27 @@
|
||||
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
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
Reference in New Issue
Block a user