# Convert a roman numeral to a number. # # If you are interested in roman numerals check out my other post # python script that takes a number and generates a roman numeral # # For a life time of knowledge checkout: # http://en.wikipedia.org/wiki/Roman_numerals # def ConvertRomanNumeralToNumber(roman_numeral): number_result = 0 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 through the roman numerals. But you see here that I sort them to # get the largest string size first: "CD" comes before "I" for numeral_value in sorted(roman_numerals, key=lambda roman: len(roman_numerals[roman]), reverse=True): keep_converting = True while keep_converting: if roman_numeral.find(roman_numerals[numeral_value]) != -1: number_result += numeral_value roman_numeral = roman_numeral.replace(roman_numerals[numeral_value], "", 1) else: keep_converting = False return number_result print(ConvertRomanNumeralToNumber("MCDXLIV")) print(ConvertRomanNumeralToNumber("MMMDCCCLXXXVIII")) print(ConvertRomanNumeralToNumber("MMMCMXCIX")) # my output: # 1444 # 3888 # 3999
A python example based blog that shows how to accomplish python goals and how to correct python errors.
Showing posts with label lambda. Show all posts
Showing posts with label lambda. Show all posts
Thursday, February 3, 2011
Python - Roman Numeral to Number Generator
Subscribe to:
Posts (Atom)