Created
June 8, 2015 19:11
-
-
Save andreagrandi/12c5cbcbe14f23f1d016 to your computer and use it in GitHub Desktop.
Transform a Roman format number in a decimal one (Python)
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
n = 'MCMXCVII' # 1997 | |
def roman_to_decimal(n): | |
roman_map = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1} | |
result = 0 | |
for i,c in enumerate(n): | |
num = roman_map[c] | |
if result == 0: | |
result += num | |
else: | |
if num <= roman_map[n[i-1]]: | |
result += num | |
else: | |
result -= roman_map[n[i-1]] | |
result += num - roman_map[n[i-1]] | |
return result | |
print roman_to_decimal(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment