Skip to content

Instantly share code, notes, and snippets.

@daniel-woods
Created April 11, 2019 19:28
Show Gist options
  • Save daniel-woods/c158c49065230eaa5b82f50fe182cb8a to your computer and use it in GitHub Desktop.
Save daniel-woods/c158c49065230eaa5b82f50fe182cb8a to your computer and use it in GitHub Desktop.
Converting Roman Numerals into Arabic numbers
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()
@daniel-woods
Copy link
Author

daniel-woods commented Apr 11, 2019

$ python roman_to_arabic.py
ROAMN: IX
ARABIC: 9
EXPECTED: 9
----
ROAMN: VIII
ARABIC: 8
EXPECTED: 8
----
ROAMN: MCMXCIV
ARABIC: 1994
EXPECTED: 1994
----
ROAMN: I
ARABIC: 1
EXPECTED: 1
----
ROAMN: VI
ARABIC: 6
EXPECTED: 6
----
ROAMN: MMMMCMXCIX
ARABIC: 4999
EXPECTED: 4999
----
ROAMN: CD
ARABIC: 400
EXPECTED: 400
----
ROAMN: III
ARABIC: 3
EXPECTED: 3
----
ROAMN: CCXXXIX
ARABIC: 239
EXPECTED: 239
----
ROAMN: IV
ARABIC: 4
EXPECTED: 4
----

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment