Created
October 11, 2022 18:45
-
-
Save TheLurps/ecc00c5f9fe25a8ba35fbba269fde1fc to your computer and use it in GitHub Desktop.
Convert roman numerals to integer in python3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| def roman2int(roman): | |
| sum = 0 | |
| previous = 0 | |
| roman_numerals = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } | |
| for c in [*roman][::-1]: | |
| current = roman_numerals[c] | |
| if previous > current: | |
| sum -= current | |
| else: | |
| sum += current | |
| previous = current | |
| return sum | |
| def main(): | |
| roman = input("Enter a roman numeral: ") | |
| print(roman2int(roman)) | |
| if __name__ == "__main__": | |
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import unittest | |
| from roman2int import roman2int | |
| class TestRoman2Int(unittest.TestCase): | |
| def test_convert(self): | |
| cases = { 'III': 3, 'IV': 4, 'IX': 9, 'LVIII': 58, 'MCMXCIV': 1994 } | |
| for roman, integer in cases.items(): | |
| self.assertEqual(roman2int(roman), integer) | |
| if __name__ == '__main__': | |
| unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment