Skip to content

Instantly share code, notes, and snippets.

@dalelane
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dalelane/78038bc7b93fd04f3848 to your computer and use it in GitHub Desktop.
Save dalelane/78038bc7b93fd04f3848 to your computer and use it in GitHub Desktop.
A roman numeral converter - http://dalelane.co.uk/blog/?p=3244
# Converting roman numerals into numbers
#
# A homework helper by Dale and Grace Lane
# 1-Nov-2014
#
# http://dalelane.co.uk/blog/?p=3244
#
# some simple helper functions to make
# the main code more readable
#
def thereAreLettersLeft(letterPosition, numberOfLetters):
return letterPosition < numberOfLetters
def convertLetterToNumber(letter):
romannumerals = {
'I' : 1,
'V' : 5,
'X' : 10,
'L' : 50,
'C' : 100,
'D' : 500,
'M' : 1000
}
return romannumerals[letter]
def thisIsTheLastLetter(letterPosition, lastLetterPosition):
return letterPosition == lastLetterPosition
def addToTotal(toAdd, total):
return toAdd + total
#
# the main roman numeral parser
#
# get the user to type in some roman numerals
romannumber = raw_input("Enter a number in roman numerals: ")
# break up the word into separate letters
letters = list(romannumber)
numberOfLetters = len(letters)
firstLetterPosition = 0
lastLetterPosition = (numberOfLetters - 1)
# adding up the total as we go - start at 0
total = 0
# start at the beginning
letterPosition = firstLetterPosition
while thereAreLettersLeft(letterPosition, numberOfLetters):
# look at the first letter
firstletter = letters[letterPosition]
# work out what it is
firstnumber = convertLetterToNumber(firstletter)
if thisIsTheLastLetter(letterPosition, lastLetterPosition):
# this is the last letter - just add the
# value on and then we're finished
total = addToTotal(firstnumber, total)
else:
# there is another letter after this - we need to
# peek at it to decide what to do next
# look at the next letter
nextletter = letters[letterPosition + 1]
# work out what it is
nextnumber = convertLetterToNumber(nextletter)
if nextnumber > firstnumber:
# next letter is bigger, so we have to
# subtract this from it
total = addToTotal((nextnumber - firstnumber), total)
# we've used the next letter, so skip over it
letterPosition = letterPosition + 1
else:
# this letter is bigger so add the value
total = addToTotal(firstnumber, total)
# move on to the next letter
letterPosition = letterPosition + 1
# finished - show our answer
print romannumber + " = " + str(total)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment