# 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
A python example based blog that shows how to accomplish python goals and how to correct python errors.
Friday, October 15, 2010
Python - Anagram generator
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())
Labels:
abstract,
inheritance,
object,
python,
super
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
Thursday, February 25, 2010
Python - a simple polymorphism example
# A quick example of polymorphism at work in python class Food(object): def __init__(self, name, calories): self.name = name self.calories = calories def tastesLike(self): raise NotImplementedException("Subclasses are responsible for creating this method") class HotDog(Food): def tastesLike(self): return "Extremely processed meat" class Hamburger(Food): def tastesLike(self): return "grilled goodness" class ChickenPatty(Food): def tastesLike(self): return "tastes like chicken" dinner = [] dinner.append(HotDog('Beef/Turkey BallPark', 230)) dinner.append(Hamburger('Lowfat Beef Patty', 260)) dinner.append(ChickenPatty('Micky Mouse shaped Chicken Tenders', 170)) # even though each course of the dinner is a differnet type # we can process them all in the same loop for course in dinner: print course.name + " is type " + str(type(course)) print " has " + str(course.calories) + " calories " print " and tastes like " + course.tastesLike() # my output: # #Beef/Turkey BallPark is type <class '__main__.HotDog'> # has 230 calories # and tastes like Extremely processed meat #Lowfat Beef Patty is type <class '__main__.Hamburger'> # has 260 calories # and tastes like grilled goodness #Micky Mouse shaped Chicken Tenders is type <class '__main__.ChickenPatty'> # has 170 calories # and tastes like tastes like chicken
Labels:
inheritance,
object,
polymorphism,
string,
type
Python - the final countdown
# There is more than one way to accomplish a task. # I needed a method to countdown from a positive # number down to 0. Here are three ways to solve # the issue. Of course there are many more possible # solutions. # # I'd like to title this post "The Final Count Down" # Listen to this tune whilst perusing the script: # www.youtube.com/watch?v=tt_ro2aerQg # Using recursion always makes the girls swoon. def recursiveCountdown(number): print number if number > 0: recursiveCountdown(number-1) # Old school while loop. This solution gets points # for being the most obvious. def whileLoopCountdown(number): while number > -1: print number number -= 1 # Using python's xrange function is the most concise. def xrangeCountdown(number): for i in xrange(number, -1, -1): print i print "It's the final countdown" number = input("Enter number: ") print "Recursive..." recursiveCountdown(number) print "While Loop..." whileLoopCountdown(number) print "xrange..." xrangeCountdown(number) # my output: # #It's the final countdown #Enter number: 5 #Recursive... #5 #4 #3 #2 #1 #0 #While Loop... #5 #4 #3 #2 #1 #0 #xrange... #5 #4 #3 #2 #1 #0
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
Labels:
glob,
os,
python,
rename,
string.replace
Subscribe to:
Posts (Atom)