Monday, April 9, 2012

Simple Roman Numeral Converter

So I was reading the daily wtf, and noticed this article. 

Since I am trying to learn python, I decided to give this little task a quick shot.

The first thing to do here is to go and read about Roman numerals.  Once you do, you will find that the only trick is that if a lower Roman numeral precedes a larger one, it actually acts as a subtract.


#!/usr/bin/env python

import sys

ROMAN_NUMERAL_DICTIONARY = {
                                'I' : 1,
                                'V' : 5,
                                'X' : 10,
                                'L' : 50,
                                'C' : 100,
                                'D' : 500,
                                'M' : 1000
                            }


def IsRomanNumeral(romanNumeralPart):
    return romanNumeralPart in ROMAN_NUMERAL_DICTIONARY

def GetDigitValueOf(romanNumeralPart):
    return ROMAN_NUMERAL_DICTIONARY[romanNumeralPart]


args = sys.argv
if (len(args) < 2):
    print "Please pass an argument to convert."
    sys.exit(0)

romanNumeral = args[1]

decimalNumber = 0
counter = 0

while counter <= (len(romanNumeral) -1):
    currentNumeral = romanNumeral[counter]
    if not IsRomanNumeral(currentNumeral):
        print "Invalid roman numeral... exiting.. "
        sys.exit(0)
    
    currentDigit = GetDigitValueOf(currentNumeral)
    if (counter + 1 >= len(romanNumeral)):
        decimalNumber = decimalNumber + currentDigit
        break
    nextDigit = GetDigitValueOf(romanNumeral[counter + 1])
    if (currentDigit < nextDigit):
        decimalNumber = decimalNumber + nextDigit - currentDigit
        counter = counter + 2
    else:
        decimalNumber = decimalNumber + currentDigit
        counter = counter + 1


print romanNumeral + "=" + str(decimalNumber)



Probably not the best python.. but I'm still learning!