Showing posts with label sorted. Show all posts
Showing posts with label sorted. Show all posts

Thursday, February 3, 2011

Python - Roman Numeral to Number Generator

# 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 
 
 

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 
 
 

Wednesday, April 14, 2010

Python - frequency and location of words in text

# Split a paragraph into lines and find 
# the frequency and line number of words. 
 
from operator import itemgetter
 
# words and locations are stored in a dict 
wordDict = {}
 
# the text we will parse 
text = ''' this is the text on line one. 
this is line two text. 
here is the text of line number three.''' 
 
 
def groupWords(text):
    lineCount = 0
    # break down by lines 
    for line in text.split('\n'):
        line = line.strip(".,!?:;'") # strip puncuation 
        lineCount += 1
        upLine = line.upper() # words are words..case no matter 
        # break line into words 
        for word in upLine.split():
            if wordDict.has_key(word):
                # then add to the key 
                tempValue = wordDict[word]
                wordDict[word] = str(tempValue) + " " + str(lineCount)
            else:
                # add it 
                wordDict[word] = " " + str(lineCount)
 
groupWords(text)
 
# alphabetical output 
for k in sorted(wordDict.iterkeys()):
    print k + str(wordDict[k])
 
# my output: 
##  HERE 3 
##  IS 1 2 3 
##  LINE 1 2 3 
##  NUMBER 3 
##  OF 3 
##  ON 1 
##  ONE 1 
##  TEXT 1 2 3 
##  THE 1 3 
##  THIS 1 2 
##  THREE 3 
##  TWO 2 
 
# most frequent style output 
# put the dict in a list 
wordList = []
for k in wordDict.iterkeys():
    wordList.append((str(len(wordDict[k].replace(' ',''))),
                    str(k),
                    wordDict[k]))
 
 
for word in sorted(wordList, key=itemgetter(0), reverse=True):
    print word[0], word[1], ":"+word[2]
 
# my output: 
##  3 TEXT : 1 2 3 
##  3 IS : 1 2 3 
##  3 LINE : 1 2 3 
##  2 THIS : 1 2 
##  2 THE : 1 3 
##  1 ON : 1 
##  1 TWO : 2 
##  1 HERE : 3 
##  1 ONE : 1 
##  1 NUMBER : 3 
##  1 OF : 3 
##  1 THREE : 3