Tuesday, September 15, 2009

Python - create static methods in a class

#create static methods in a python class

import math

class MyStaticClass:
def getSqrt(num):
return math.sqrt(num)
def getHalf(num):
return num/2
# labels the methods as static
getSqrt = staticmethod(getSqrt)
getHalf = staticmethod(getHalf)

MyStaticClass.getSqrt(144)
12.0
MyStaticClass.getHalf(20)
10

Python - reorder a sentence alphabetically

# reorder the words in a sentence alphabetically


def sentenceAlphabetizer(sentence):
    words = sentence.split(' ')
    words.sort()
    sentence = ""
    for word in words:
        sentence += word + " "
    return sentence.strip()



if __name__ == '__main__':
    print sentenceAlphabetizer("basic applepie zoo party")

#output:
#   'applepie basic party zoo'

Friday, September 4, 2009

Python reverse word order of a sentence

# reverse the order of words in a sentence (python 2.6.1)
#   you may also be interested 
#  in alphabetizing the words in a sentence 

def reverseWordOrderOfSentence(sentence):


    #break the sentence into words with split()
    words = sentence.split(' ')


    #reverse the order of the words list
    #in python 2.6.1 a list.reverse() is done to the calling list object

    # older versions return a reversed list..... so
    # words = words.reverse()
    words.reverse()


    #iterate through and build the new sentence
    newSentence = ""

    for word in words:
        newSentence += " " + word


    #return and strip out beginning or trailing white space

    return newSentence.strip()


if __name__ == '__main__':
    print reverseWordOrderOfSentence("Hooray for Pythonic Prose")

#input sentence:
# # "Hooray for Pythonic Prose"

#
#output:
# "Prose Pythonic for Hooray"