Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Tuesday, May 24, 2011

Python - Determine Primality of a number

 
# Determining primality by using a simple trial division test. 
# 
# This approach tests whether n is a multiple of an integer i 
# between 2 and √n.  If it is a multiple of any of these integers 
# then it is not a prime. 
 
import math
import time
 
def isPrime(n):
    for i in range(2, int(math.sqrt(n))):
        if n % i == 0:
            return False
    return True
 
def withTimer(n):
    start = time.time()
    prime = isPrime(n)
    elapsed = time.time() - start
    print("{0}   {1}    time:{2}").format(prime, n, elapsed)
 
# Primality of 2 to 13 digit known primes 
withTimer(13)
withTimer(715827883)
withTimer(2932031007403)
 
# test non primes 
withTimer(52)
withTimer(5820384023)
withTimer(2059384726303)
 
# my output: 
# True   13    time:0.0 
# True   715827883    time:0.00300002098083 
# True   2932031007403    time:0.521000146866 
# False   52    time:0.0 
# False   5820384023    time:0.000999927520752 
# False   2059384726303    time:0.029000043869 
 
 
 

Thursday, March 3, 2011

Python - rock paper scissors game from the command line

# Here is a command line Rock Paper Scissor game. 
# As you can see by my output I am not so good. ;) 
 
import random
 
class RockPaperScissors():
    """ 
        Play Rock Paper Scissors with Python CLI! 
    """ 
    def __init__(self):
        # setup the random chooser for the computer 
        self.rand = random.Random()
        self.cScore = 0 # computer score 
        self.hScore = 0 # human score 
    def getComputerMove(self):
        return self.rand.randrange(1,4)
    def getHumanMove(self):
        while True:
            choice = input("Make your move: rock (1), paper (2), scissors(3): ")
            choice = choice.strip()
            if choice == "1" or choice == "rock":
                return 1
            if choice == "2" or choice == "paper":
                return 2
            if choice == "3" or choice == "scissors":
                return 3
            print("I didn't understand your choice. Please try again")
    def decideWinner(self, c, h):
        """ 
        rock breaks scissors 
        paper covers rock 
        scissors cuts paper 
        """ 
        if (c, h) == (1, 3):
            print("rock breaks scissors")
            print("computer wins")
            self.cScore+=1
        elif (h, c) == (1, 3):
            print("rock breaks scissors")
            print("you win")
            self.hScore+=1
        elif (c, h) == (2, 1):
            print("paper covers rock")
            print("computer wins")
            self.cScore+=1
        elif (h, c) == (2, 1):
            print("paper covers rock")
            print("you win")
            self.hScore+=1
        elif (c, h) == (3, 2):
            print("scissors cuts paper")
            print("computer wins")
            self.cScore+=1
        elif (h, c) == (3, 2):
            print("scissors cuts paper")
            print("you win")   
            self.hScore+=1
        else:
            print("Tie!")
 
    def showScore(self):
        print("Score:")
        print("Computer: ", self.cScore, " You: ", self.hScore)
 
    def playAgain(self):
        yn = input("Play Again? (y/n):  ")
        yn = yn.strip()
        yn = yn.lower()
        if yn == "n" or yn == "no":
            return False
        return True
 
    def gameLoop(self):
        while True:
            print()
            print()
            computerMove = self.getComputerMove()
            humanMove = self.getHumanMove()
            print()
            print("you chose: ", humanMove, " computer chose: ", computerMove)
            self.decideWinner(computerMove, humanMove)
            print()
            self.showScore()
            if self.playAgain() == False:
                return 
 
if __name__ == '__main__':
    rps = RockPaperScissors()
    rps.gameLoop()
    
 
## my output: 
## Make your move: rock (1), paper (2), scissors(3): 2 
## 
## you chose:  2  computer chose:  3 
## scissors cuts paper 
## computer wins 
## 
## Score: 
## Computer:  1  You:  0 
## Play Again? (y/n):  y 
## 
## 
## Make your move: rock (1), paper (2), scissors(3): 1 
## 
## you chose:  1  computer chose:  1 
## Tie! 
## 
## Score: 
## Computer:  1  You:  0 
## Play Again? (y/n):  y 
## 
## 
## Make your move: rock (1), paper (2), scissors(3): 3 
## 
## you chose:  3  computer chose:  1 
## rock breaks scissors 
## computer wins 
## 
## Score: 
## Computer:  2  You:  0 
 
 

Python - Compute the factorial of N with recursion (among others)

# Calculating the factorial of a number 
# is a good way to practice recursion. Below 
# are examples of both recursive and iterative 
# approaches to calculating a factorial. Of course 
# python has its own builtin math module that 
# can also take care of factorials. 
 
import math
 
# A recursive function to calculate the 
# factorial of N 
def recursiveFactorial(n):
    if n == 1:
        return n
    return n * recursiveFactorial(n - 1)
 
# Iterative calculation of the factorial 
# of N 
def iterativeFactorial(n):
    result = 1
    while n > 1:
        result *= n
        n = n-1
    return result
 
# Builtin python math.factorial of N 
def pythonLib(n):
    return math.factorial(n)
 
print("Iterative factorial of 5: ", iterativeFactorial(5))
print("Recursive factorial of 5: ", recursiveFactorial(5))
print("math.factorial of 5: ", pythonLib(5))
 
print("Iterative factorial of 10: ", iterativeFactorial(10))
print("Recursive factorial of 10: ", recursiveFactorial(10))
print("math.factorial of 10: ", pythonLib(10))
 
print("Iterative factorial of 15: ", iterativeFactorial(15))
print("Recursive factorial of 15: ", recursiveFactorial(15))
print("math.factorial of 15: ", pythonLib(15))
 
 
# my results: 
# Iterative factorial of 5:  120 
# Recursive factorial of 5:  120 
# math.factorial of 5:  120 
# Iterative factorial of 10:  3628800 
# Recursive factorial of 10:  3628800 
# math.factorial of 10:  3628800 
# Iterative factorial of 15:  1307674368000 
# Recursive factorial of 15:  1307674368000 
# math.factorial of 15:  1307674368000 
 
 

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 
 
 

Friday, October 15, 2010

Python - Anagram generator

# python anagram generator 
# 
# This anagram generator uses a 
# text file as a reference for 
# appropriate words. 
# 
# The word file I used is in the 
# following format (each word has 
# it's own line): 
# 
# act 
# addition 
# adjustment 
# advertisement 
# after 
# again 
# against 
# ... and on and on... 
# 
 
def isAnagramOf(attempt, original):
    # all the same case 
    attempt = attempt.strip()
    if len(attempt) < 1: # only actual words 
        return False
    attempt, original = attempt.lower(), original.lower()
    for character in attempt:
        position = original.find(character)
        if (position == -1):
            return False
        original = original.replace(character, '', 1)
    return True
 
def getAnagramsFor(text):
    anagrams = []
    wordlist = open("wordlist.txt", 'r')
    for line in wordlist:
        line = line.strip("\n") #strip the carriage return 
        if isAnagramOf(line, text):
            anagrams.append(line)
    return anagrams
 
matching_anagrams = getAnagramsFor("pythonic prose")
print(len(matching_anagrams), "total anagrams generated")
for ana in matching_anagrams:
    print(ana)
 
 
# my output: 
# 
# 66 total anagrams generated 
# chest 
# chin 
# copper 
# copy 
# cry 
# he 
# history 
# hope 
# ... skip a few ... 
# theory 
# thin 
# this 
# tin 
# to 
# toe 
# top 
# yes 
 

Python - Anagram detector

# A python Anagram detector 
# manipulate anagrams with python 
# 
# Python could no doubt solve this in 
# many ways.... here is one: 
 
 
 
# determine whether a string is an anagram 
# of another string 
def isAnagramOf(attempt, original):
    # all the same case 
    attempt, original = attempt.lower(), original.lower()
    for character in attempt:
        position = original.find(character)
        if (position == -1):
            return False
        original = original.replace(character, '', 1)
    return True
 
 
original = "Texas Ranger" 
 
 
print("Is Rage an anagram of", original, "=",
      isAnagramOf("Anger", original))
print("Is Extra Angers an anagram of", original, "=",
      isAnagramOf("Extra Angers", original))
print("Is Extra Angered an anagram of", original, "=",
      isAnagramOf("Extra Angered", original))
 
#   my output: 
#   Is Rage an anagram of Texas Ranger = True 
#   Is Extra Angers an anagram of Texas Ranger = True 
#   Is Extra Angered an anagram of Texas Ranger = False 
 
 

Python - palindrome detector

# palindrome detector
#
# parse text and print out palindromes
 
 
# make a map to remove punctuation
punc = {" ":'', ",":'',
        ".":'', "!":'',
        "?":'', "'":'',
        '"':'', ':':'',
        '\n':''}
puncMap = str.maketrans(punc)
 
# determines whether given text is a palindrome
def isPalindrome(text):
    # change to all the same case
    text = text.lower()
    # remove punctuation
    text = text.translate(puncMap)
    # to count as a palindrome it must have
    # at least 2 valid characters
    if (len(text) < 2):
        return False
    # palindrome if it reads the same
    # front or backwards
    return text == text[::-1]
 
 
givenText = """
    Hi Mom, welcome. A man, a plan, a canal, panama. And 
    other text. 
    """
 
# first check the whole text
if (isPalindrome(givenText)):
    print("The entire text: '" + givenText.strip() + "' is a palindrome.")
 
# now check by sentence
for sentence in givenText.split('.'):
    if (isPalindrome(sentence)):
        print("The sentence: '" + sentence.strip() + "' is a palindrome.")
 
# now check every word
for word in givenText.split(' '):
    if (isPalindrome(word)):
        print("The word: '" + word.strip() + "' is a palindrome.")
 
# my output:
# The sentence: 'A man, a plan, a canal, panama' is a palindrome.
# The word: 'Mom,' is a palindrome.
 
    
 
 

Friday, August 20, 2010

Python - limit cpu percentage for script

# It is sometimes useful to monitor how much cpu time or 
# cpu percentage your script is consuming. 
# This script will limit the cpu usage of your script 
 
# This example demostrates how to calculate the system 
# and user cpu time and cpu percentage 
 
# Note: this example is in python 3.0 
#   however, it is easily ported back to 2.x 
#   by replaceing print() with print 
 
import os
import time
 
def getPercentage(unew, uold, start):
    """ 
    calculate the percentage of cpu time 
    """ 
    return 100 * (float(unew) - float(uold)) / (time.time()-float(start))
 
def looper(timeCount, percentageGoal):
    """ 
    loop over many tasks and keep the total cpu percentage 
    consumtion to a desired level 
    """ 
    start = time.time()
    time.sleep(0.1)
    keepLooping = True
    uold, sold, cold, c, e = os.times()
    percentage = 0.0
    while keepLooping:
        unew, snew, cnew, c, e = os.times()
        # since we are calculating the times from before we started looping the 
        # percentages will be averaged over the duration of the script. 
        print ("user %", percentage)
 
        # This just toggles to stop looping 
        # when a time has been reached. In a real 
        # script you would check for more work and 
        # toggle off when there is no more work to 
        # be done. 
        if time.time()-start > timeCount:
            keepLooping = False
        #else: 
        #    print( time.time()-start) 
 
        # do work: 
        #   In order for this script to actually help limit 
        #   the cpu usage you would need to break your script into 
        #   sections. 
        #   For example: if you were going to iterate through a large 
        #       list of data and perform actions on the contents 
        #       of the list then you should perform on action here 
        #       and keep looping through until all the actions 
        #       are accomplished. 
        # 
        # in this case we're just eating cpu so we get some numbers 
        print("do work...")
        for i in range(1,1000000):
            b = 8*342*i*234
 
        # tone back cpu usage 
        while True:
            percentage = getPercentage(unew, uold, start)
            if percentage > percentageGoal:
                time.sleep(0.1)
            else:
                break;
 
if __name__ == '__main__':
    # loop through work (for 4 seconds) and keep the cpu % 
    # to less than 30% 
    looper(4, 30)
 
## my output: 
##      user % 0.0 
##      do work... 
##      user % 0.0 
##      do work... 
##      user % 29.6673831301 
##      do work... 
##      user % 29.1137166495 
##      do work... 
##      user % 29.7617156875 
##      do work... 
##      user % 29.5707887319 
##      do work... 
##      user % 29.8122197706 
##      do work... 
##      user % 29.3053848216 
##      do work... 
##      user % 29.9385051866 
##      do work... 
 
 

Monday, July 26, 2010

Python - simple event programming

# simple event programming with python 
# this example is written in p3k ... but can 
# be easily ported to 2.x 
 
# Event Thrower 
class QueenBee(object):
    def __init__(self):
        self.subscriber_to_event_list = []
    def addSubscriberToEvent(self, subscriber, eventText):
        ''' subscribe bees to eventText commands ''' 
        se = (subscriber, eventText)
        self.subscriber_to_event_list.append(se)
    def issueCommand(self, eventText):
        ''' raise event to followers ''' 
        for se in self.subscriber_to_event_list:
            sub = se[0]
            eve = se[1]
            if eve == eventText:
                sub(eve)
 
# event subscriber 
class WorkerBee(object):
    def __init__(self, name, event):
        self.name = name
    def receiveEvent(self, eventName):
        ''' begin work from here ''' 
        print (self.name + " 'By Your Command,' received event: " + eventName)
 
 
 
 
 
qb = QueenBee()
# worker bees 
bList = []
# subscribe bees to commands (events) 
for i in range(10):
    bName = "b"+str(i)
    eventText = "Do More Work" 
    b = WorkerBee(bName, eventText)
    qb.addSubscriberToEvent(b.receiveEvent, eventText)
    bList.append(b)
 
# queen bee issues command that bees are not subscribed to 
print("unscribed to command output: ")
qb.issueCommand("make me a sandwhich")
# nothing happens 
 
print()
print("subscribed event issued:")
# queen bee issues subscribed to event 
qb.issueCommand("Do More Work")
 
 
 
 

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 
 
 

Monday, April 12, 2010

Python - Finding GCD with Euclids Algorithm

# Implementing the Euclidean Algorithm
# is simple in python.
#
# Euclid's algorithm is used to efficiently
# find two numbers greatest common divisor (GCD)
 
# Division based Euclidean algorithm
def gcd(a,b):
    while b != 0:
        temp = b
        b = a%b
        a = temp
    return a
 
# Recursive based Euclidean algorithm
def recursiveGCD(a,b):
    if b==0:
        return a
    else:
        return recursiveGCD(b, a%b)
 
 
# just to prove they both work the same:
def findGCD(a,b):
    divisionStyle = gcd(a,b)
    recursiveStyle = recursiveGCD(a,b)
    if divisionStyle != recursiveStyle:
        return "Fail...GCDs differ"
    else:
        return divisionStyle
 
print findGCD(1071, 462)
print findGCD(5, 10)
print findGCD(5214, 24324)
 
# my output:
#   21
#   5
#   6
 
 
 

Wednesday, April 7, 2010

Python - Tkinter frontend example to ping

# python GUI example using Tkinter

# Everyone likes to ping servers and what
# not so this example is a front end
# to the well used ping command.
#
# Python has quite a few different

# frameworks to choose from. For
# this example I'll use the basic
# Tkinter that ships with most python
# installers.

#

from Tkinter import *
from subprocess import PIPE, Popen

class App:
    def __init__(self, master):
        frame = Frame(master)
        frame.grid()

        # create and position widgets

        self.label = Label(frame, text="Enter IP Address or Server Name:")
        self.label.grid(row=0, column=0, sticky=W)

        self.textbox = Text(frame, height=1, width=40)
        self.textbox.grid(row=1, column=0, columnspan=2, sticky=W)
        self.textbox.insert(END, "www.google.com")

        self.resultsBox = Text(frame, height=10, width=60)
        self.resultsBox.grid(row=3, column=0, columnspan=3, sticky=W)

        self.hi_there = Button(frame, text="Ping",
                               width=10, command=self.doPing)
        self.hi_there.grid(row=1, column=2, sticky=W)

    def doPing(self):
        # reset result box
        self.resultsBox.delete(1.0, END)
        # get text

        texttext = self.textbox.get(1.0, END)
        exelist = ['ping', '-n', '1']
        exelist.append(texttext)
        # Execute command (these ping commands are windows specific).
        # In Linux you would use the '-c' to specify count.

        exe = Popen(exelist, shell=False, stdout=PIPE, stderr=PIPE)
        out, err = exe.communicate()
        while out:
            self.resultsBox.insert(END, out)
            out, err = exe.communicate()

root = Tk()
app = App(root)
root.mainloop()


Python - event programming example

# Event programming in python

# Python doesn't have a standard 'only' way
# of doing events.  You can create your own
# pythonic events like so.
#

# In the example you'll notice that the Musician
# handles all the recieved events.  You could
# have just as easily created specific event
# handlers for the reacting classes.  Whatever

# makes sense for your application is good.
# Python is flexible!
#
# This would be a way that
# python could implement events or delegates.

import time

# Important class that will raise events
class Orchestrator(object):
    def __init__(self):
        # You'll notice that the events instances

        # of the subscribers are stored in these
        # lists.  Having a list allows multiple
        # subscribers to the event.
        self.armsRaise = []
        self.pointsAtMe = []
    def subscribeToArmRaiseEvent(self, event):
        # we append the instance methods to the

        # event lists
        self.armsRaise.append(event)
    def subscribeToPointsAtMeEvent(self, event):
        # we append the instance methods to the
        # event lists

        self.pointsAtMe.append(event)
    def raiseArmRaiseEvent(self):
        # iterating through the lists we call
        # each of the instance methods
        for i in self.armsRaise:
            i("Arms Raised")
    def raisePointsAtMeEvent(self):
        # iterating through the lists we call

        # each of the instance methods
        for i in self.pointsAtMe:
            i("Points at me")
    def raiseArms(self):
        self.raiseArmRaiseEvent()
    def pointAtMusician(self):
        self.raisePointsAtMeEvent()


# class that reacts to events
class Musician(object):
    def __init__(self, name):
        self.name = name
    def receiveEvent(self, msg):
        if msg == "Arms Raised":
            print self.name + " hold up instrument"

        if msg == "Points at me":
            print self.name + " play instrument"

# players

o = Orchestrator()
m = Musician("trumpet")
m2 = Musician("clarinet")

# Subscribe to the Orchestrator events:
# We're really just assigning instance methods
# of our Musician objects to the Orchestra object.

o.subscribeToArmRaiseEvent(m.receiveEvent)
o.subscribeToPointsAtMeEvent(m.receiveEvent)
o.subscribeToArmRaiseEvent(m2.receiveEvent)
o.subscribeToPointsAtMeEvent(m2.receiveEvent)

# Concert begins
o.raiseArms()
# ... other actions and events
# represented by:
print "do bee doo be dooo be do do do"

time.sleep(4)
# finally gets to your part of the song
o.pointAtMusician()

# my output:
#   trumpet hold up instrument
#   clarinet hold up instrument

#   do bee doo be dooo be do do do
#   trumpet play instrument
#   clarinet play instrument


Wednesday, March 31, 2010

Python - insult generator

# negative reinforcement through insults

#
#
# Sometimes negative reinforcement is the way to go.
# For the times when you need a kick in the pants
# rather than a pat on the back I whipped up this

# insult generator.
# It will churn out more insults then you can shake
# a stick at.

import random

class insultGenerator(object):
    def __init__(self):
        # setup the lists of insult fodder

        self.nounList = ['loser',
                         'jerk',
                         'nerd',
                         'doodie head',
                         'butthead',
                         'bonehead',
                         'dunce',
                         'moron',
                         'nerf herder']
        self.adjectiveList = ['smelly',
                              'ugly',
                              'gimpy',
                              'slimy',
                              'crabby',
                              'scabby',
                              'scratchy']
        self.connectorList = ['are one',
                              'are the biggest',
                              'are becoming a']
    def getInsult(self):
        insult = "you"

        # connector phrase
        connector = random.randint(1, len(self.connectorList))
        insult += " " + self.connectorList[connector-1]

        # adjectives
        adjCount = random.randint(2,4)
        random.shuffle(self.adjectiveList)
        for i in xrange(0,adjCount):
            if i != 0:
                insult += ", "

            else:
                insult += " "
            insult += self.adjectiveList[i]

        # ending noun
        noun = random.randint(1,len(self.nounList))
        insult += " " + self.nounList[noun-1]
        return insult


# a little example to get some insults flowing
if __name__ == '__main__':
    ig = insultGenerator()
    print ig.getInsult()
    print ig.getInsult()
    print ig.getInsult()
    print ig.getInsult()



# my output:
#   you are one ugly, slimy, scabby loser
#   you are the biggest scabby, slimy nerd
#   you are becoming a scabby, ugly, gimpy butthead

#   you are one slimy, smelly, crabby bonehead



Saturday, March 27, 2010

Python - unit tests with the unittest module

# python has a built in unit test module "unittest"
#

# Using python's unittest module is similar to NUnit
# or JUnit (if you are familiar with those).
#


import unittest


# my example function
# Normally you would have the class in its own
# file and then just import ExampleFunction into

# the unit test file.
class ExampleFunction(object):
    def __init__(self):
        self.example = 0
        self.example2 = 1
        self.example3 = 2
    def processVariable(self, item):
        item *= self.example2 * self.example3
        return item
    def setExampleVariables(self, example):
        self.example = example
        self.example2 = self.example + 1
        self.example3 = self.example2 + 1


# The test class inherits from unittest's TestCase.
# Inheriting ensures that the tests will run when you
# call unittest.Main()
class TestExampleFunction(unittest.TestCase):
    def setUp(self):
        self.ef = ExampleFunction()
    def test_defaults(self):
        # There are a lot types of asserts available

        # I only demo the assertEqual here.
        self.assertEqual(self.ef.example, 0, "example is not set to 0")
        self.assertEqual(self.ef.example2, 1, "example2 is not set to 1")
        self.assertEqual(self.ef.example3, 2, "example3 is not set to 2")
    def test_processVariable(self):
        self.assertEqual(self.ef.processVariable(1), 2, "example error message")
    def test_setExampleVariables(self):
        self.ef.setExampleVariables(5)
        self.assertEqual(self.ef.example, 5, "example is not set to 0")
        self.assertEqual(self.ef.example2, 6, "example2 is not set to 1")
        self.assertEqual(self.ef.example3, 7, "example3 is not set to 2")


if __name__ == '__main__':
    unittest.main()


# My Output:
#    ...
#    -------------------------------------
#    Ran 3 tests in 0.000s
#
#    OK


Tuesday, March 23, 2010

Python - calling super class methods from derived classes

# An inheritance, abstract classes, and
# calling super class methods from derived

# classes example

class AbstractBot(object):
    def __init__(self):
        self.size = 0
        self.speed = 1
        self.pos = [0,0]
    def applyPos(self, xy):
        self.pos[0] += xy[0] * self.speed
        self.pos[1] += xy[1] * self.speed
    def getCurrentPos(self):
        return self.pos


class WalkingBot(AbstractBot):
    def applyPos(self, xy):
        super(WalkingBot, self).applyPos(xy)
        print "step, step"

class DrivingBot(AbstractBot):
    def applyPos(self, xy):
        super(DrivingBot, self).applyPos(xy)
        print "vroom, vroom"

class RunningBot(AbstractBot):
    def __init__(self):
        super(RunningBot, self).__init__()
        self.speed = 5
    def applyPos(self, xy):
        super(RunningBot, self).applyPos(xy)
        print "trot, trot"

bot1 = WalkingBot()
bot2 = DrivingBot()
bot3 = RunningBot()
bots = [bot1, bot2, bot3]

distance = (1,1)

for step in xrange(3):
    for bot in bots:
        bot.applyPos(distance)
        print 'position: ' + str(bot.getCurrentPos())
        


Monday, March 8, 2010

Python - creating an interface with python

# python doesn't formally support an interface.
# You can work around this and support the spirit

# of an interface by creating abstract classes that
# have empty methods that just raise exceptions if
# haven't been implemented.

class Vehicle:
    def __init__(self, model):
        self.model = model
    def returnModel(self):
        raise NotImplementedError("Subclass must implement")
    def calculateTaxes(self):
        raise NotImplementedError("Subclass must implement")


class Toyota(Vehicle):
    pass


t = Toyota("Carolla")
t.returnModel()

#output:
# NotImplementedError: Subclass must implement

# You are required to implement the defined methods ( just

# like when using an interface

Wednesday, February 24, 2010

Python - Bulk rename a directory of files

 
# I found myself with the need to rename my video 
# collection.  For some reason I decided that using 
# spaces in a file name is lame....underscores should 
# always be used.  After two or three files of manually 
# renaming I decided that python could do all the 
# work for me. 
 
import os
import glob
 
# My video collection is all matroska files.  So 
# the extension of them all is *.mkv format. 
files_to_change = '*.mkv' 
 
# new and old versions of a space 
lame_space = ' ';
cool_space = '_';
 
# use glob to gather a list of matching files 
for f in glob.glob(files_to_change):
        f2 = f
        f2 = f2.replace(lame_space, cool_space)
        # add a little status for instant gratification 
        print 'renaming: ', f, ' -> ', f2
        os.rename(f, f2)
 
print 'All Done' 
 
 
## my output: 
# 
# renaming:  Me at home.mkv  ->  Me_at_home.mkv 
# renaming:  Max in kid pool.mkv  ->  Max_in_kid_pool.mkv 
# ........ < and so on > 
# All Done 
 
 

Thursday, November 19, 2009

Python - processing command line arguments

# python scripts are often run from the
# command line.

# python can retrieve and use command line
# arguments with the sys module.

import sys

# all arguments are stored in the sys.argv list
print "number of arguments passed: ", len(sys.argv)

# process through the argument list

for argument in sys.argv:
    print argument

# my input/output:
#    python commandlinearguments.py one two three four five six seven
#    number of arguments passed:  8
#    commandlinearguments.py

#    one
#    two
#    three
#    four
#    five
#    six
#    seven