Created
April 11, 2019 19:28
-
-
Save daniel-woods/c158c49065230eaa5b82f50fe182cb8a to your computer and use it in GitHub Desktop.
Converting Roman Numerals into Arabic numbers
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 convert(numeral): | |
| romans = { | |
| "I": 1, | |
| "V": 5, | |
| "X": 10, | |
| "L": 50, | |
| "C": 100, | |
| "D": 500, | |
| "M": 1000 | |
| } | |
| arabic = [] | |
| total = 0 | |
| # Convert the Roman Numerals to their Arabic equivalent | |
| # "VII" would become [5, 1, 1] | |
| for letter in numeral: | |
| arabic.append(romans[letter]) | |
| # Cycle through the list backwards. Read Numerals Right-to-Left. | |
| # [5, 1, 1] | |
| for k in range(len(arabic))[::-1]: | |
| if k == len(arabic) - 1: | |
| total += arabic[k] | |
| prev = arabic[k] | |
| continue | |
| else: | |
| if arabic[k] >= prev: | |
| # If the current number is greater/equal to the previous | |
| # We add it to the total | |
| total += arabic[k] | |
| else: | |
| # Otherwise, if it's less, we subtract. | |
| total -= arabic[k] | |
| prev = arabic[k] | |
| return total | |
| def main(): | |
| _input = { | |
| "I": 1, | |
| "IV": 4, | |
| "VI": 6, | |
| "IX": 9, | |
| "CD": 400, | |
| "III": 3, | |
| "VIII": 8, | |
| "CCXXXIX": 239, | |
| "MCMXCIV": 1994, | |
| "MMMMCMXCIX": 4999 | |
| } | |
| for i in _input: | |
| total = convert(i) | |
| print("ROAMN: {}\nARABIC: {}\nEXPECTED: {}\n----".format(i, total, _input[i])) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.