Created
July 3, 2023 09:14
-
-
Save asedmammad/cb510ce51c724b8655346aab6b419f99 to your computer and use it in GitHub Desktop.
Roman to Number and Number to Roman
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
| def number_to_roman(n): # Number to Roman encoder | |
| roman_numerals = {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'} | |
| roman_num = '' | |
| for value, numeral in sorted(roman_numerals.items(), reverse=True): | |
| while n >= value: | |
| roman_num += numeral | |
| n -= value | |
| return roman_num | |
| def roman_to_number(roman_num): # Roman to Number decoder | |
| roman_numerals = {'M': 1000, 'CM': 900, 'D': 500, 'CD': 400, 'C': 100, 'XC': 90, 'L': 50, 'XL': 40, 'X': 10, 'IX': 9, 'V': 5, 'IV': 4, 'I': 1} | |
| num = 0 | |
| i = 0 | |
| while i < len(roman_num): | |
| for value, numeral in roman_numerals.items(): | |
| if roman_num[i:i+len(value)] == value: | |
| num += numeral | |
| i += len(value) | |
| break | |
| else: | |
| return None # Invalid Roman numeral | |
| return num |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment