Thursday, February 3, 2011

Python - Roman Numeral Generator

# Convert a number to a roman numeral. 
# 
# If you are interested in roman numerals check out my other post to convert roman numerals back to numbers 
# python script that takes roman numerals and generates numbers. 
# 
# To increase your life time of knowledge read up on roman numerals: 
# http://en.wikipedia.org/wiki/Roman_numerals 
 
 
def ConvertNumberToRomanNumeral(number):
    roman_numeral_result = "" 
    
    # Roman numeral dict. Place approved roman numeral key:value pairs 
    # in the dict and they will be used. 
    roman_numerals = {
        1:"I", 4:"IV", 5:"V", 9:"IX",
        10:"X", 40:"XL", 50:"L",
        90:"XC", 100:"C", 400:"CD",
        500:"D", 900:"CM", 1000:"M"}
 
    # Iterate from highest to lowest through the roman numerals. 
    for numeral_value in sorted(roman_numerals.keys(), reverse=True):
 
        # Continue replacing large roman numerals while the number is 
        # high enough. 
        while (number >= numeral_value):
            # Build the Roman Numeral string. 
            roman_numeral_result += roman_numerals[numeral_value]
            # Decrease the working number by the roman numeral value just 
            # added to the roman numeral result. 
            number -= numeral_value
 
    return roman_numeral_result
 
 
print(ConvertNumberToRomanNumeral(1444))
print(ConvertNumberToRomanNumeral(3888))
print(ConvertNumberToRomanNumeral(3999))
 
# my output: 
#  MCDXLIV 
#  MMMDCCCLXXXVIII 
#  MMMCMXCIX 
 
 

No comments:

Post a Comment