id
int64
0
25.6k
text
stringlengths
0
4.59k
19,800
elif value = on [ , , , elif value = on [ , , , , elseon [ , , , , , for in onself pips[isetfill(self foregroundthe version without lists required lines of code to accomplish the same task but we can do even better than this notice that this code still uses the if-elif structure to determine which pips should be turned on the correct list of indexes is determined by valuewe can make this decision table-driven instead the idea is to use list where each item in the list is itself list of pip indexes for examplethe item in position should be the list [ , , ]since these are the pips that must be turned on to show value of here is how table-driven approach can be codedontable [][ ][ , ][ , , ][ , , , ][ , , , , ][ , , , , , for pip in self pipsself pip setfill(self backgroundon ontable[valuefor in onself pips[isetfill(self foregroundi have called the table of pip indexes ontable notice that padded the table by placing an empty list in the first position if value is the dieview will be blank now we have reduced our lines of code to seven in additionthis version is much easier to modifyif you want to change which pips are displayed for various valuesyou simply modify the entries in ontable there is one last issue to address the ontable will remain unchanged throughout the life of any particular dieview rather than (re)creating this table each time new value is displayedit would be better to create the table in the constructor and save it in an instance variable putting the definition of ontable into __init__ yields this nicely completed classdieview py from graphics import class dieview""dieview is widget that displays graphical representation of standard six-sided die "" an even better approach would be to use class variablebut class variables are beyond the scope of the current discussion
19,801
def __init__(selfwincentersize)"""create view of diee gdie(mywinpoint( , ) creates die centered at ( , having sides of length ""first define some standard values self win win self background "whitecolor of die face self foreground "blackcolor of the pips self psize size radius of each pip hsize size half of size offset hsize distance from center to outer pips create square for the face cxcy center getx()center gety( point(cx-hsizecy-hsizep point(cx+hsizecy+hsizerect rectangle( , rect draw(winrect setfill(self backgroundcreate circles for standard pip locations self pips self __makepip(cx-offsetcy-offset)self __makepip(cx-offsetcy)self __makepip(cx-offsetcy+offset)self __makepip(cxcy)self __makepip(cx+offsetcy-offset)self __makepip(cx+offsetcy)self __makepip(cx+offsetcy+offsetcreate table for which pips are on for each value self ontable [][ ][ , ][ , , ][ , , , ][ , , , , ][ , , , , , self setvalue( def __makepip(selfxy)"""internal helper method to draw pip at ( , )""pip circle(point( , )self psizepip setfill(self background
19,802
pip setoutline(self backgroundpip draw(self winreturn pip def setvalue(selfvalue)""set this die to display value ""turn all the pips off for pip in self pipspip setfill(self backgroundturn the appropriate pips back on for in self ontable[value]self pips[isetfill(self foregroundthis example also showcases the advantages of encapsulation that talked about in we have significantly improved the implementation of the dieview classbut we have not changed the set of methods that it supports we can substitute this improved version into any program that uses dieview without having to modify any of the other code the encapsulation of objects allows us to build complex software systems as set of "pluggable modules case studypython calculator the reworked dieview class shows how lists can be used effectively as instance variables of objects interestinglyour pips list and ontable list contain circles and listsrespectivelywhich are themselves objects by nesting and combining collections and objects we can devise elegant ways of storing data in our programs we can even go one step further and view program itself as collection of data structures (collections and objectsand set of algorithms that operate on those data structures nowif program contains data and operationsone natural way to organize the program is to treat the entire application itself as an object calculator as an object as an examplewe'll develop program that implements simple python calculator our calculator will have buttons for the ten digits ( - ) decimal point )four operations (+-*/)and few special keys"cto clear the display"<-to backspace over characters in the displayand "=to do the calculation we'll take very simple approach to performing calculations as buttons are clickedthe corresponding characters will show up in the displayallowing the user to create formula when the "=key is pressedthe formula will be evaluated and the resulting value shown in the display figure shows snapshot of the calculator in action basicallywe can divide the functioning of the calculator into two partscreating the interface and interacting with the user the user interface in this case consists of display widget and bunch
19,803
figure python calculator in action of buttons we can keep track of these gui widgets with instance variables the user interaction can be managed by set of methods that manipulate the widgets to implement this division of laborwe will create calculator class that represents the calculator in our program the constructor for the class will create the initial interface we will make the calculator respond to user interaction by invoking special run method constructing the interface let' take detailed look at the constructor for the calculator class firstwe'll need to create graphics window to draw the interface def __init__(self)create the window for the calculator win graphwin("calculator"win setcoords( , , , win setbackground("slategray"self win win the coordinates for the window were chosen to simplify the layout of the buttons in the last linethe window object is tucked into an instance variable so that other methods can refer to it the next step is to create the buttons we will reuse the button class from last since there are lot of similar buttonswe will use list to store them here is the code that creates the button listcreate list of buttons start with all the standard sized buttons bspecs gives center coords and label of buttons
19,804
bspecs [( , ,' ')( , ,')( , ,' ')( , ,' ')( , ,' ')( , ,'+')( , ,'-')( , ,' ')( , ,' ')( , ,' ')( , ,'*')( , ,'/')( , ,' ')( , ,' ')( , ,' ')( , ,'<-'),( , ,' ')self buttons [for (cx,cy,labelin bspecsself buttons append(button(self win,point(cx,cy) ,label)create the larger '=button self buttons append(button(self winpoint( , ) "=")activate all buttons for in self buttonsb activate(study this code carefully button is normally specified by providing center pointwidthheightand label typing out calls to the button constructor with all this information for each button would be tedious rather than creating the buttons directlythis code first creates list of button specificationsbspecs this list of specifications is then used to create the buttons each specification is tuple consisting of the and coordinates of the center of the button and its label tuple looks like list except that it is enclosed in round parentheses (instead of square brackets [ tuple is just another kind of sequence in python tuples are like lists except that tuples are immutable--the items can' be changed if the contents of sequence won' be changed after it is createdusing tuple is more efficient than using list the next step is to iterate through the specification list and create corresponding button for each entry take look at the loop headingfor (cx,cy,labelin bspecsaccording to the definition of for loopthe tuple (cx,cy,labelwill be assigned each successive item in the list bspecs put another wayconceptuallyeach iteration of the loop starts with an assignment (cx,cy,labelof courseeach item in bspecs is also tuple when tuple of variables is used on the left side of an assignmentthe corresponding components of the tuple on the right side are unpacked into the variables on the left side in factthis is how python actually implements all simultaneous assignments the first time through the loopit is as if we had done this simultaneous assignmentcxcylabel " each time through the loopanother tuple from bspecs is unpacked into the variables in the loop heading the values are then used to create button that is appended to the list of buttons after all of the standard-sized buttons have been createdthe larger button is created and tacked onto the list
19,805
self buttons append(button(self winpoint( , ) "=") could have written line like this for each of the previous buttonsbut think you can see the appeal of the specification-list/loop approach for creating the similar buttons in contrast to the buttonscreating the calculator display is quite simple the display will just be rectangle with some text centered on it we need to save the text object as an instance variable so that its contents can be accessed and changed during processing of button clicks here is the code that creates the displaybg rectangle(point , )point( , )bg setfill('white'bg draw(self wintext text(point( , )""text draw(self wintext setface("courier"text setstyle("bold"text setsize( self display text processing buttons now that we have an interface drawnwe need method that actually gets the calculator running our calculator will use classic event loop that waits for button to be clicked and then processes that button let' encapsulate this in method called run def run(self)while truekey self getkeypress(self processkey(keynotice that this is an infinite loop to quit the programthe user will have to "killthe calculator window all that' left is to implement the getkeypress and processkey methods getting key presses is easywe continue getting mouse clicks until one of those mouse clicks is on button to determine whether button has been clickedwe loop through the list of buttons and check each one the result is nested loop def getkeypress(self)waits for button to be clicked returns the label of the button that was clicked while trueloop for each mouse click self win getmouse(for in self buttonsloop for each button if clicked( )return getlabel(method exit
19,806
you can see how having the buttons in list is big win here we can use for loop to look at each button in turn if the clicked point turns out to be in one of the buttonsthe label of that button is returnedproviding an exit from the otherwise infinite while loop the last step is to update the display of the calculator according to which button was clicked this is accomplished in processkey basicallythis is multi-way decision that checks the key label and takes the appropriate action digit or operator is simply appended to the display if key contains the label of the buttonand text contains the current contents of the displaythe appropriate line of code looks like thisself display settext(text+keythe clear key blanks the display self display settext(""the backspace strips off one character self display settext(text[:- ]finallythe equal key causes the expression in the display to be evaluated and the result displayed tryresult eval(textexceptresult 'errorself display settext(str(result)the try-except here is necessary to catch run-time errors caused by entries that are not legal python expressions if an error occursthe calculator will display error rather than causing the program to crash here is the complete programcalc pyw - four function calculator using python arithmetic illustrates use of objects and lists to build simple gui from graphics import from button import button class calculatorthis class implements simple calculator gui def __init__(self)create the window for the calculator win graphwin("calculator"win setcoords( , , , win setbackground("slategray"
19,807
self win win now create the widgets self __createbuttons(self __createdisplay(def __createbuttons(self)create list of buttons start with all the standard sized buttons bspecs gives center coords and label of buttons bspecs [( , ,' ')( , ,')( , ,' ')( , ,' ')( , ,' ')( , ,'+')( , ,'-')( , ,' ')( , ,' ')( , ,' ')( , ,'*')( , ,'/')( , ,' ')( , ,' ')( , ,' ')( , ,'<-'),( , ,' ')self buttons [for (cx,cy,labelin bspecsself buttons append(button(self win,point(cx,cy) ,label)create the larger button self buttons append(button(self winpoint( , ) "=")activate all buttons for in self buttonsb activate(def __createdisplay(self)bg rectangle(point , )point( , )bg setfill('white'bg draw(self wintext text(point( , )""text draw(self wintext setface("courier"text setstyle("bold"text setsize( self display text def getbutton(self)waits for button to be clicked and returns the label of the button that was clicked while truep self win getmouse(for in self buttonsif clicked( )return getlabel(method exit
19,808
def processbutton(selfkey)updates the display of the calculator for press of this key text self display gettext(if key =' 'self display settext(""elif key ='<-'backspaceslice off the last character self display settext(text[:- ]elif key ='='evaluate the expresssion and display the result the try except mechanism "catcheserrors in the formula being evaluated tryresult eval(textexceptresult 'errorself display settext(str(result)elsenormal key pressappend it to the end of the display self display settext(text+keydef run(self)infinite 'event loopto process button clicks while truekey self getbutton(self processbutton(keythis runs the program if __name__ ='__main__'first create calculator object thecalc calculator(now call the calculator' run method thecalc run(notice especially the very end of the program to run the applicationwe create an instance of the calculator class and then call its run method non-sequential collections python provides another built-in data type for collectionscalled dictionary while dictionaries are incredibly usefulthey are not as common in other languages as lists (arraysthe example programs in the rest of the book will not use dictionariesso you can skip the rest of this section if
19,809
data collections you've learned all you want to about collections for the moment dictionary basics lists allow us to store and retrieve items from sequential collections when we want to access an item in the collectionwe look it up by index--its position in the collection many applications require more flexible way to look up information for examplewe might want to retrieve information about students or employees based on their social security numbers in programming terminologythis is key-value pair we access the value (student informationassociated with particular key (social security numberif you think bityou can come up with lots of other examples of useful key-value pairsnames and phone numbersusernames and passwordszip codes and shipping costsstate names and capitalssales items and quantity in stocketc collection that allows us to look up information associated with arbitrary keys is called mapping python dictionaries are mappings some other programming languages provide similar structures called hashes or associative arrays dictionary can be created in python by listing keyvalue pairs inside of curly braces here is simple dictionary that stores some fictional usernames and passwordspasswd {"guido":"superprogrammer""turing":"genius""bill":"monopoly"notice that keys and values are joined with ":"and commas are used to separate the pairs the main use for dictionary is to look up the value associated with particular key this is done through indexing notation passwd["guido"'superprogrammerpasswd["bill"'monopolyin general[returns the object associated with the given key dictionaries are mutablethe value associated with key can be changed through assignment passwd["bill""bluescreenpasswd {'turing''genius''bill''bluescreen''guido''superprogrammer'in this exampleyou can see that the value associated with 'billhas changed to 'bluescreenalso notice that the dictionary prints out in different order from how it was originally created this is not mistake mappings are inherently unordered internallypython stores dictionaries in way that makes key lookup very efficient when dictionary is printed outthe order of keys will
19,810
look essentially random if you want to keep collection of items in certain orderyou need sequencenot mapping to summarizedictionaries are mutable collections that implement mapping from keys to values our password example showed dictionary having strings as both keys and values in generalkeys can be any immutable typeand values can be any type at allincluding programmerdefined classes python dictionaries are very efficient and can routinely store even hundreds of thousands of items dictionary operations like listspython dictionaries support number of handy built-in operations you have already seen how dictionaries can be defined by explicitly listing the key-value pairs in curly braces you can also extend dictionary by adding new entries suppose new user is added to our password system we can expand the dictionary by assigning password for the new username passwd['newuser''imanewbiepasswd {'turing''genius''bill''bluescreen''newuser''imanewbie''guido''superprogrammer'in facta common method for building dictionaries is to start with an empty collection and add the key-value pairs one at time suppose that usernames and passwords were stored in file called passwordswhere each line of the file contains username and password with space between we could easily create the passwd dictionary from the file passwd {for line in open('passwords',' ')userpass line split(passwd[userpass to manipulate the contents of dictionarypython provides the following methodsmethod in keys(values(items(get(del [clear(for in meaning returns true if dictionary contains the specified keyfalse if it doesn' returns sequence keys returns sequence of values returns sequence of tuples (key,valuerepresenting the key-value pairs if dictionary has key returns its valueotherwise returns default deletes the specified entry deletes all entries loop over the keys
19,811
data collections these methods are mostly self-explanatory for illustrationhere is an interactive session using our password dictionarylist(passwd keys()['turing''bill''newuser''guido'list(passwd values()['genius''bluescreen''imanewbie''superprogrammer'list(passwd items()[('turing''genius')('bill''bluescreen'),('newuser''imanewbie'),('guido''superprogrammer')"billin passwd true 'fredin passwd false passwd get('bill','unknown''bluescreenpasswd get('john','unknown''unknownpasswd clear(passwd {example programword frequency let' write program that analyzes text documents and counts how many times each word appears in the document this kind of analysis is sometimes used as crude measure of the style similarity between two documents and is also used by automatic indexing and archiving programs (such as internet search enginesat the highest levelthis is just multi-accumulator problem we need count for each word that appears in the document we can use loop that iterates through each word in the document and adds one to the appropriate count the only catch is that we will need hundreds or thousands of accumulatorsone for each unique word in the document this is where (pythondictionary comes in handy we will use dictionary where the keys are strings representing words in the document and the values are ints that count how many times the word appears let' call our dictionary counts to update the count for particular wordwwe just need line of code something like thiscounts[wcounts[ this says to set the count associated with word to be one more than the current count for there is one small complication with using dictionary here the first time we encounter wordit will not yet be in counts attempting to access non-existent key produces run-time keyerror to guard against thiswe need decision in our algorithm
19,812
if is already in countsadd one to the count for elseset count for to this decision ensures that the first time word is encounteredit will be entered into the dictionary with count of one way to implement this decision is to use the in operator if in countscounts[wcounts[ elsecounts[ more elegant approach is to use the get method counts[wcounts get( , if is not already in the dictionarythis get will return and the result is that the entry for is set to the dictionary updating code will form the heart of our program we just need to fill in the parts around it the first task is to split our text document into sequence of words in the processwe will also convert all the text to lowercase (so occurrences of "foomatch "foo"and eliminate punctuation (so "foo,matches "foo"here' the code to do thatfname input("file to analyze"read file as one long string text open(fname," "read(convert all letters to lower case text text lower(replace each punctuation character with space for ch in '!"#$%&()*+,/:;?@[\\]^ '{|}~'text text replace(ch"split string at whitespace to form list of words words text split(now we can easily loop through the words to build the counts dictionary counts {for in wordscounts[wcounts get( ,
19,813
data collections our last step is to print report that summarizes the contents of counts one approach might be to print out the list of words and their associated counts in alphabetical order here' how that could be doneget list of words that appear in document uniquewords list(counts keys()put list of words in alphabetical order uniquewords sort(print words and associated counts for in uniquewordsprint(wcounts[ ]for large documenthoweverthis is unlikely to be useful there will be far too many wordsmost of which only appear few times more interesting analysis is to print out the counts for the most frequent words in the document in order to do thatwe will need to create list that is sorted by counts (most to fewestand then select the first items in the list we can start by getting list of key-value pairs using the items method for dictionaries items list(counts items()here items will be list of tuples ( [('foo', )('bar', )('spam', )]if we simply sort this list (items sort()python will put them in standard order unfortunatelywhen python compares tuplesit orders them by componentsleft to right since the first component of each pair is the worditems sort(will put this list in alphabetical orderwhich is not what we want to sort our list of items according to frequencywe can use the key-function trick again this timeour function will take pair as parameter and return the second item in the pair def byfreq(pair)return pair[ notice that tupleslike listsare indexed starting at so returning pair[ hands back the frequency part of the tuple with this comparison functionit is now simple matter to sort our items by frequency items sort(key=byfreqbut we're not quite finished yet when we have multiple words with the same frequencyit would be nice if those words appeared in the list in alphabetical order within their frequency group that iswe want the list of pairs primarily sorted by frequencybut sorted alphabetically within each level how can we handle this double-sortednessif you look at the documentation for the python sort method (via help([sort]you'll see that this method performs "stable sort *in placeas you can probably inferbeing "in place
19,814
means that the method modifies the list that it is applied to rather than producing newsortedversion of the list but the critical point for us here is the word "stable sorting algorithm is stable if equivalent items (items that have equal keysstay in the same relative position to each other in the resulting list as they were in the original since the python sorting algorithm is stableif all the words were in alphabetical order before sorting them by frequencythen words having the same frequency will still be in alphabetical order to get the result we wantwe just need to sort the list twicefirst by words and then by frequency items sort(items sort(key=byfreqreverse=trueorders pairs alphabetically orders by frequency have added one last wrinkle here supplying the keyword parameter reverse and setting it to true tells python to sort the list in reverse order the resulting list will go from highest frequency to lowest now that our items are sorted in order from most to least frequentwe are ready to print report of the most frequent words here' loop that does the trickfor in range( )wordcount items[iprint("{ : }format(wordcountthe loop index is used to get the next next pair from the list of itemsand that item is unpacked into its word and count components the word is then printed left-justified in fifteen spacesfollowed by the count right-justified in five spaces that about does it here is the complete programwordfreq py def byfreq(pair)return pair[ def main()print("this program analyzes word frequency in file"print("and prints report on the most frequent words \ "get the sequence of words from the file fname input("file to analyze"text open(fname,' 'read(text text lower(for ch in '!"#$%&()*+,/:;?@[\\]^ '{|}~'text text replace(ch' an experienced python programmer would probably write this loop body as single line using the tuple unpacking operator *print(" : format(*items[ ]the curious should consult the python documentation to learn more about this handy operator
19,815
words text split(construct dictionary of word counts counts {for in wordscounts[wcounts get( , output analysis of most frequent words eval(input("output analysis of how many words")items list(counts items()items sort(items sort(key=byfreqreverse=truefor in range( )wordcount items[iprint("{ : }format(wordcount)if __name__ ='__main__'main(just for funhere' the result of running this program to find the twenty most frequent words in draft of the book you're reading right nowthis program analyzes word frequency in file and prints report on the most frequent words file to analyzebook txt output analysis of how many words the of to is that and in we this for you program be it are
19,816
as can will an summary this has discussed techniques for handling collections of related information here is summary of some key ideasa list object is mutable sequence of arbitrary objects items can be accessed by indexing and slicing the items of list can be changed by assignment python lists are similar to arrays in other programming languages python lists are more flexible because their size can vary and they are heterogeneous python lists also support number of useful methods one particularly important data processing operation is sorting python lists have sort method that can be customized by supplying suitable key function this allows programs to sort lists of arbitrary objects classes can use lists to maintain collections stored as instance variables oftentimes using list is more flexible than using separate instance variables for examplea gui application might use list of buttons instead of an instance variable for each button an entire program can be viewed as collection of data and set of operations--an object this is common approach to structuring gui applications python dictionary implements an arbitrary mapping from keys into values it is very useful for representing non-sequential collections exercises review questions true/false the median is the average of set of data standard deviation measures how spread out data set is arrays are usually heterogeneousbut lists are homogeneous python list cannot grow and shrink in size unlike stringspython lists are not mutable
19,817
list must contain at least one item items can be removed from list with the del operator comparison function returns either true or false tuple is similar to immutable list python dictionary is kind of sequence multiple choice where mathematicians use subscriptingcomputer programmers use aslicing bindexing cpython dcaffeine which of the following is not built-in sequence operation in pythonasorting bconcatenation cslicing drepetition the method that adds single item to the end of list is aextend badd cplus dappend which of the following is not python list methodaindex binsert cget dpop which of the following is not characteristic of python listait is an object bit is sequence cit can hold objects dit is immutable which of the following expressions correctly tests if is evenax = beven(xcnot odd(xdx = the parameter xbar in stddev is whatamedian bmode cspread dmean what keyword parameter is used to send key-function to the sort methodareverse breversed ccmp dkey which of the following is not dictionary methodaget bkeys csort dclear the items dictionary method returns (naint bsequence of tuples cbool ddictionary
19,818
discussion given the initial statements import string [ , , , [' ',' ',' 'show the result of evaluating each of the following sequence expressions(as ( (cs [ (ds [ : (es [- given the same initial statements as in the previous problemshow the values of and after executing each of the following statements treat each part independently ( assume that and start with their original values each time(as remove( (bs sort((cs append([ index(' ')](ds pop( pop( )(es insert( [ ]' 'programming exercises modify the statistics package from the so that client programs have more flexibility in computing the mean and/or standard deviation specificallyredesign the library to have the following functionsmean(numsreturns the mean of numbers in nums stddev(numsreturns the standard deviation of nums meanstddev(numsreturns both the mean and standard deviation of nums extend the gpasort program so that it allows the user to sort file of students based on gpanameor credits your program should prompt for the input filethe field to sort onand the output file extend your solution to the previous problem by adding an option to sort the list in either ascending or descending order
19,819
give the program from the previous exercise(sa graphical interface you should have entrys for the input and output file names and button for each sorting order bonusallow the user to do multiple sorts and add button for quitting most languages do not have the flexible built-in list (arrayoperations that python has write an algorithm for each of the following python operations and test your algorithm by writing it up in suitable function for exampleas functionreverse(mylistshould do the same as mylist reverse(obviouslyyou are not allowed to use the corresponding python method to implement your function (acount(mylistx(like mylist count( )(bisin(mylistx(like in mylist)(cindex(mylistx(like mylist index( )(dreverse(mylist(like mylist reverse()(esort(mylist(like mylist sort() write and test function shuffle(mylistthat scrambles list into random orderlike shuffling deck of cards write and test function innerprod( , )that computes the inner product of two (same lengthlists the inner product of and is computed asn- xi yi = write and test function removeduplicates(somelistthat removes duplicate values from list one disadvantage of passing function to the list sort method is that it makes the sorting slowersince this function is called repeatedly as python needs to compare various items an alternative to creating special key function is to create "decoratedlist that will sort in the desired order using the standard python ordering for exampleto sort student objects by gpawe could first create list of tuples [(gpa student )(gpa ,student )and then sort this list without passing key function these tuples will get sorted into gpa order the resulting list can then be traversed to rebuild list of student objects in gpa order redo the gpasort program using this approach the sieve of eratosthenes is an elegant algorithm for finding all of the prime numbers up to some limit the basic idea is to first create list of numbers from to the first number is removed from the listand announced as prime numberand all multiples of this number up to are removed from the list this process continues until the list is empty for exampleif we wished to find all the primes up to the list would originally contain the is removed and announced to be prime then and
19,820
are removedsince they are multiples of that leaves repeating the process is announced as prime and removedand is removed because it is multiple of that leaves and the algorithm continues by announcing that is prime and removing it from the list finally is announced and removedand we're done write program that prompts user for and then uses the sieve algorithm to find all the primes less than or equal to write an automated censor program that reads in the text from file and creates new file where all of the four-letter words have been replaced by "****you can ignore punctuationand you may assume that no words in the file are split across multiple lines extend the program from the previous exercise to accept file of censored words as another input the words in the original file that appear in the censored words file are replaced by an appropriate number of "*" write program that creates list of card objects (see programming exercise from and prints out the cards grouped by suit and in rank order within suit your program should read the list of cards from filewhere each line in the file represents single card with the rank and suit separated by space hintfirst sort by rank and then by suit extend the previous program to analyze list of five cards as poker hand after printing the cardsthe program categorizes accordingly royal flush jackqueenkingaceall of the same suit straight flush five ranks in rowall of the same suit four of kind four of the same rank full house three of one rank and two of another flush five cards of the same suit straight five ranks in row three of kind three of one rank (but not full house or four of kindtwo pair two each of two different ranks pair two of the same rank (but not two pairthree or four of kindx high if none of the previous categories fitx is the value of the highest rank for exampleif the largest rank is the hand is "jack high create class deck that represents deck of cards your class should have the following methodsconstructor creates new deck of cards in standard order shuffle randomizes the order of the cards dealcard returns single card from the top of the deck and removes the card from the deck
19,821
cardsleft returns the number of cards remaining in the deck test your program by having it deal out sequence of cards from shuffled deck where is user input you could also use your deck object to implement blackjack simulation where the pool of cards is finite see programming exercises and in create class called statset that can be used to do simple statistical calculations the methods for the class are__init__(selfcreates statset with no data in it addnumber(self,xx is number adds the value to the statset mean(selfreturns the mean of the numbers in this statset median(selfreturns the median of the numbers in this statset stddev(selfreturns the standard deviation of the numbers in this statset count(selfreturns the count of numbers in this statset min(selfreturns the smallest value in this statset max(selfreturns the largest value in this statset test your class with program similar to the simple statistics program from this in graphics applicationsit often useful to group separate pieces of drawing together into single object for examplea face might be drawn from individual shapesbut then positioned as whole group create new class graphicsgroup that can be used for this purpose graphicsgroup will manage list of graphics objects and have the following methods__init__(selfanchoranchor is point creates an empty group with the given anchor point getanchor(selfreturns clone of the anchor point addobject(selfgobjectgobject is graphics object adds gobject to the group move(selfdx,dymove all of the objects in the group (including the anchor pointdraw(selfwindraws all the objects in the group into win the anchor point is not drawn undraw(selfundraws all the objects in the group use your new class to write program that draws some simple picture with multiple components and move it to wherever the user clicks extend the random walk program from (programming exercise to keep track of how many times each square of the sidewalk is crossed start your walker in the middle of sidewalk of length where is user inputand continue the simulation until it drops off one of the ends then print out the counts of how many times each square was landed on create and test set class to represent classical set your sets should support the following methods
19,822
set(elementscreate set (elements is the initial list of items in the setaddelement(xadds to the set deleteelement(xremoves from the setif present if is not in the setthe set is left unchanged member(xreturns true if is in the set and false otherwise intersection(set returns new set containing just those elements that are common to this set and set union(set returns new set containing all of elements that are in this setset or both subtract(set returns new set containing all the elements of this set that are not in set
19,823
data collections
19,824
object-oriented design objectives to understand the process of object-oriented design to be able to read and understand object-oriented programs to understand the concepts of encapsulationpolymorphism and inheritance as they pertain to object-oriented design and programming to be able to design moderately complex software using object-oriented design the process of ood now that you know some data structuring techniquesit' time to stretch your wings and really put those tools to work most modern computer applications are designed using data-centered view of computing this so-called object-oriented design (oodprocess is powerful complement to top-down design for the development of reliablecost-effective software systems in this we will look at the basic principles of ood and apply them in couple of case studies the essence of design is describing system in terms of magical black boxes and their interfaces each component provides set of services through its interface other components are users or clients of the services client only needs to understand the interface of servicethe details of how that service is implemented are not important in factthe internal details may change radically and not affect the client at all similarlythe component providing the service does not have to consider how the service might be used the black box just has to make sure that the service is faithfully delivered this separation of concerns is what makes the design of complex systems possible in top-down designfunctions serve the role of our magical black boxes client program can use function as long as it understands what the function does the details of how the task is accomplished are encapsulated in the function definition
19,825
object-oriented design in object-oriented designthe black boxes are objects the magic behind objects lies in class definitions once suitable class definition has been writtenwe can completely ignore how the class works and just rely on the external interface--the methods this is what allows you to draw circles in graphics windows without so much as glance at the code in the graphics module all the nitty-gritty details are encapsulated in the class definitions for graphwin and circle if we can break large problem into set of cooperating classeswe drastically reduce the complexity that must be considered to understand any given part of the program each class stands on its own object-oriented design is the process of finding and defining useful set of classes for given problem like all designit is part art and part science there are many different approaches to oodeach with its own special techniquesnotationsgurusand textbooks can' pretend to teach you all about ood in one short on the other handi' not convinced that reading many thick volumes will help much either the best way to learn about design is to do it the more you designthe better you will get just to get you startedhere are some intuitive guidelines for object-oriented design look for object candidates your goal is to define set of objects that will be helpful in solving the problem start with careful consideration of the problem statement objects are usually described by nouns you might underline all of the nouns in the problem statement and consider them one by one which of them will actually be represented in the programwhich of them have "interestingbehaviorthings that can be represented as primitive data types (numbers or stringsare probably not important candidates for objects things that seem to involve grouping of related data items ( coordinates of point or personal data about an employeeprobably are identify instance variables once you have uncovered some possible objectsthink about the information that each object will need to do its job what kinds of values will the instance variables havesome object attributes will have primitive valuesothers might themselves be complex types that suggest other useful objects/classes strive to find good "homeclasses for all the data in your program think about interfaces when you have identified potential object/class and some associated datathink about what operations would be required for objects of that class to be useful you might start by considering the verbs in the problem statement verbs are used to describe actions--what must be done list the methods that the class will require remember that all manipulation of the object' data should be done through the methods you provide refine the nontrivial methods some methods will look like they can be accomplished with couple of lines of code other methods will require considerable work to develop an algorithm use top-down design and stepwise refinement to flesh out the details of the more difficult methods as you go alongyou may very well discover that some new interactions with other classes are neededand this might force you to add new methods to other classes sometimes you may discover need for brand-new kind of object that calls for the definition of another class
19,826
design iteratively as you work through the designyou will bounce back and forth between designing new classes and adding methods to existing classes work on whatever seems to be demanding your attention no one designs program top to bottom in linearsystematic fashion make progress wherever it seems progress needs to be made try out alternatives don' be afraid to scrap an approach that doesn' seem to be working or to follow an idea and see where it leads good design involves lot of trial and error when you look at the programs of othersyou are seeing finished worknot the process they went through to get there if program is well designedit probably is not the result of first try fred brooksa legendary software engineercoined the maxim"plan to throw one away often you won' really know how system should be built until you've already built it the wrong way keep it simple at each step in the designtry to find the simplest approach that will solve the problem at hand don' design in extra complexity until it is clear that more complex approach is needed the next sections will walk you through couple case studies that illustrate aspects of ood once you thoroughly understand these examplesyou will be ready to tackle your own programs and refine your design skills case studyracquetball simulation for our first case studylet' return to the racquetball simulation from you might want to go back and review the program that we developed the first time around using top-down design the crux of the problem is to simulate multiple games of racquetball where the ability of the two opponents is represented by the probability that they win point when they are serving the inputs to the simulation are the probability for player athe probability for player band the number of games to simulate the output is nicely formatted summary of the results in the original version of the programwe ended game when one of the players reached total of points this time aroundlet' also consider shutouts if one player gets to before the other player has scored pointthe game ends our simulation should keep track of both the number of wins for each player and the number of wins that are shutouts candidate objects and methods our first task is to find set of objects that could be useful in solving this problem we need to simulate series of racquetball games between two players and record some statistics about the series of games this short description already suggests one way of dividing up the work in the program we need to do two basic thingssimulate game and keep track of some statistics let' tackle simulation of the game first we can use an object to represent single game of racquetball game will have to keep track of information about two players when we create
19,827
object-oriented design new gamewe will specify the skill levels of the players this suggests classlet' call it rballgamewith constructor that requires parameters for the probabilities of the two players what does our program need to do with gameobviouslyit needs to play it let' give our class play method that simulates the game until it is over we could create and play racquetball game with two lines of codethegame rballgame(probaprobbthegame play(to play lots of gameswe just need to put loop around this code that' all we really need in rballgame to write the main program let' turn our attention to collecting statistics about the games obviouslywe will have to keep track of at least four counts in order to print summary of our simulationswins for awins for bshutouts for aand shutouts for we will also print out the number of games simulatedbut this can be calculated by adding the wins for and here we have four related pieces of information rather than treating them independentlylet' group them into single object this object will be an instance of class called simstats simstats object will keep track of all the information about series of games we have already analyzed the four crucial pieces of information now we have to decide what operations will be useful for starterswe need constructor that initializes all of the counts to we also need way of updating the counts as each new game is simulated let' give our object an update method the update of the statistics will be based on the outcome of game we will have to send some information to the statistics object so that the update can be done appropriately an easy approach would be to just send the entire game and let update extract whatever information it needs finallywhen all of the games have been simulatedwe need to print out report of the results this suggests printreport method that prints out nice report of the accumulated statistics we have now done enough design that we can actually write the main function for our program most of the details have been pushed off into the definition of our two classes def main()printintro(probaprobbn getinputs(play the games stats simstats(for in range( )thegame rballgame(probaprobbcreate new game thegame play(play it stats update(thegameget info about completed game print the results stats printreport( have also used couple helper functions to print an introduction and get the inputs you should have no trouble writing these functions
19,828
now we have to flesh out the details of our two classes the simstats class looks pretty easy-let' tackle that one first implementing simstats the constructor for simstats just needs to initialize the four counts to here is an obvious approachclass simstatsdef __init__(self)self winsa self winsb self shutsa self shutsb now let' take look at the update method it takes game as normal parameter and must update the four counts accordingly the heading of the method will look like thisdef update(selfagame)but how exactly do we know what to dowe need to know the final score of the gamebut this information resides inside of agame rememberwe are not allowed to directly access the instance variables of agame we don' even know yet what those instance variables will be our analysis suggests the need for new method in the rballgame class we need to extend the interface so that agame has way of reporting the final score let' call the new method getscores and have it return the score for player and the score for player now the algorithm for update is straightforward def update(selfagame)ab agame getscores(if ba won the game self winsa self winsa if = self shutsa self shutsa elseb won the game self winsb self winsb if = self shutsb self shutsb we can complete the simstats class by writing method to print out the results our printreport method will generate table that shows the winswin percentageshutoutsand shutout percentage for each player here is sample outputsummary of games
19,829
wins (totalshutouts (winsplayer player it is easy to print out the headings for this tablebut the formatting of the lines takes little more care we want to get the columns lined up nicelyand we must avoid division by zero in calculating the shutout percentage for player who didn' get any wins let' write the basic methodbut procrastinate bit and push off the details of formatting the line into another methodprintline the printline method will need the player label ( or )number of wins and shutoutsand the total number of games (for calculation of percentagesdef printreport(self)print nicely formatted report self winsa self winsb print("summary of" "games:\ "print(wins (totalshutouts (wins"print(""self printline(" "self winsaself shutsanself printline(" "self winsbself shutsbnto finish out the classwe implement the printline method this method will make heavy use of string formatting good start is to define template for the information that will appear in each line def printline(selflabelwinsshutsn)template "player { }:{ : ({ : %}{ : ({ })if wins = avoid division by zeroshutstr "elseshutstr "{ : %}format(float(shuts)/winsprint(template format(labelwinsfloat(wins)/nshutsshutstr)notice how the shutout percentage is handled the main template includes it as fifth slotand the if statement takes care of formatting this piece to prevent division by zero implementing rballgame now that we have wrapped up the simstats classwe need to turn our attention to rballgame summarizing what we have decided so farthis class needs constructor that accepts two probabilities as parametersa play method that plays the gameand getscores method that reports the scores what will racquetball game need to knowto actually play the gamewe have to remember the probability for each playerthe score for each playerand which player is serving if you think
19,830
about this carefullyyou will see that probability and score are properties related to particular playerswhile the server is property of the game between the two players that suggests that we might simply consider that game needs to know who the players are and which is serving the players themselves can be objects that know their probability and score thinking about the rballgame class this way leads us to design some new objects if the players are objectsthen we will need another class to define their behavior let' name that class player player object will keep track of its probability and current score when player is first created the probability will be supplied as parameterbut the score will just start out at we'll flesh out the design of player class methods as we work on rballgame we are now in position to define the constructor for rballgame the game will need instance variables for the two players and another variable to keep track of which player is serving class rballgamedef __init__(selfprobaprobb)self playera player(probaself playerb player(probbself server self playera player always serves first sometimes it helps to draw picture to see the relationships among the objects that we are creating suppose we create an instance of rballgame like thisthegame rballgame figure shows an abstract picture of the objects created by this statement and their interrelationships player rballgame playeraprob score playerbserverplayer prob score figure abstract view of rballgame object oknow that we can create an rballgamewe need to figure out how to play it going back to the discussion of racquetball from we need an algorithm that continues to serve rallies
19,831
and either award points or change the server as appropriate until the game is over we can translate this loose algorithm almost directly into our object-based code firstwe need loop that continues as long as the game is not over obviouslythe decision of whether the game has ended or not can only be made by looking at the game object itself let' just assume that an appropriate isover method can be written the beginning of our play method can make use of this (yet-to-be-writtenmethod def play(self)while not self isover()inside of the loopwe need to have the serving player serve andbased on the resultdecide what to do this suggests that player objects should have method that performs serve after allwhether the serve is won or not depends on the probability that is stored inside of each player object we'll just ask the server if the serve is won or lost if self server winsserve()based on this resultwe either award point or change the server to award pointwe need to change player' score this again requires the player to do somethingnamely increment the score changing serverson the other handis done at the game levelsince this information is kept in the server instance variable of rballgame putting it all togetherhere is our play methoddef play(self)while not self isover()if self server winsserve()self server incscore(elseself changeserver(as long as you remember that self is an rballgamethis code should be clear while the game is not overif the server wins serveaward point to the serverotherwise change the server of coursethe price we pay for this simple algorithm is that we now have two new methods (isover and changeserverthat need to be implemented in the rballgame class and two more (winsserve and incscorefor the player class before attacking these new methodslet' go back and finish up the other top-level method of the rballgame classnamely getscores this one just returns the scores of the two players of coursewe run into the same problem again it is the player objects that actually know the scoresso we will need method that asks player to return its score def getscores(self)return self playera getscore()self playerb getscore(this adds one more method to be implemented in the player class make sure you put that on our list to complete later
19,832
to finish out the rballgame classwe need to write the isover and changeserver methods given what we have developed already and our previous version of this programthese methods are straightforward 'll leave those as an exercise for you at the moment if you're looking for my solutionsskip to the complete code at the end of this section implementing player in developing the rballgame classwe discovered the need for player class that encapsulates the service probability and current score for player the player class needs suitable constructor and methods for winsserveincscoreand getscore if you are getting the hang of this object-oriented approachyou should have no trouble coming up with constructor we just need to initialize the instance variables the player' probability will be passed as parameterand the score starts at def __init__(selfprob)create player with this probability self prob prob self score the other methods for our player class are even simpler to see if player wins servewe compare the probability to random number between and def winsserve(self)return random(<self prob to give player pointwe simply add one to the score def incscore(self)self score self score the final method just returns the value of the score def getscore(self)return self score initiallyyou may think that it' silly to create class with bunch of oneor two-line methods actuallyit' quite common for well-modularizedobjected-oriented program to have lots of trivial methods the point of design is to break problem down into simpler pieces if those pieces are so simple that their implementations are obviousthat gives us confidence that we must have gotten it right the complete program that pretty much wraps up our object-oriented version of the racquetball simulation the complete program follows you should read through it and make sure you understand exactly what each class does and how it does it if you have questions about any partsgo back to the discussion above to figure it out
19,833
objrball py -simulation of racquet game illustrates design with objects from random import random class playera player keeps track of service probability and score def __init__(selfprob)create player with this probability self prob prob self score def winsserve(self)returns boolean that is true with probability self prob return random(<self prob def incscore(self)add point to this player' score self score self score def getscore(self)returns this player' current score return self score class rballgamea rballgame represents game in progress game has two players and keeps track of which one is currently serving def __init__(selfprobaprobb)create new game having players with the given probs self playera player(probaself playerb player(probbself server self playera player always serves first def play(self)play the game to completion while not self isover()if self server winsserve()self server incscore(elseself changeserver(
19,834
def isover(self)returns game is finished ( one of the players has wona, self getscores(return = or = or ( = and = or ( == and = def changeserver(self)switch which player is serving if self server =self playeraself server self playerb elseself server self playera def getscores(self)returns the current scores of player and player return self playera getscore()self playerb getscore(class simstatssimstats handles accumulation of statistics across multiple (completedgames this version tracks the wins and shutouts for each player def __init__(self)create new accumulator for series of games self winsa self winsb self shutsa self shutsb def update(selfagame)determine the outcome of agame and update statistics ab agame getscores(if ba won the game self winsa self winsa if = self shutsa self shutsa elseb won the game self winsb self winsb if = self shutsb self shutsb
19,835
def printreport(self)print nicely formatted report self winsa self winsb print("summary of" "games:\ "print(wins (totalshutouts (wins"print(""self printline(" "self winsaself shutsanself printline(" "self winsbself shutsbndef printline(selflabelwinsshutsn)template "player { }:{ : ({ : %}{ : ({ })if wins = avoid division by zeroshutstr "elseshutstr "{ : %}format(float(shuts)/winsprint(template format(labelwinsfloat(wins)/nshutsshutstr)def printintro()print("this program simulates games of racquetball between two"print('players called "aand "bthe ability of each player is'print("indicated by probability ( number between and that"print("the player wins the point when serving player always"print("has the first serve \ "def getinputs()returns the three simulation parameters eval(input("what is the prob player wins serve") eval(input("what is the prob player wins serve") eval(input("how many games to simulate")return abn def main()printintro(probaprobbn getinputs(play the games stats simstats(for in range( )thegame rballgame(probaprobbcreate new game thegame play(play it
19,836
stats update(thegame extract info print the results stats printreport(main(input("\npress to quit" case studydice poker back in suggested that objects are particularly useful for the design of graphical user interfaces want to finish up this by looking at graphical application using some of the widgets that we developed in previous program specification our goal is to write game program that allows user to play video poker using dice the program will display hand consisting of five dice the basic set of rules is as followsthe player starts with $ each round costs $ to play this amount is subtracted from the player' money at the start of the round the player initially rolls completely random hand ( all five dice are rolledthe player gets two chances to enhance the hand by rerolling some or all of the dice at the end of the handthe player' money is updated according to the following payout schedulehand pay two pairs three of kind full house ( pair and three of kind four of kind straight ( - or - five of kind ultimatelywe want this program to present nice graphical interface our interaction will be through mouse clicks the interface should have the following characteristicsthe current score (amount of moneyis constantly displayed the program automatically terminates if the player goes broke
19,837
object-oriented design the player may choose to quit at appropriate points during play the interface will present visual cues to indicate what is going on at any given moment and what the valid user responses are identifying candidate objects our first step is to analyze the program description and identify some objects that will be useful in attacking this problem this is game involving dice and money are either of these good candidates for objectsboth the money and an individual die can be simply represented as numbers by themselvesthey do not seem to be good object candidates howeverthe game uses five diceand this sounds like collection we will need to be able to roll all the dice or selection of dice as well as analyze the collection to see what it scores we can encapsulate the information about the dice in dice class here are few obvious operations that this class will have to implementconstructor create the initial collection rollall assign random values to each of the five dice roll assign random value to some subset of the dicewhile maintaining the current value of others values return the current values of the five dice score return the score for the dice we can also think of the entire program as an object let' call the class pokerapp pokerapp object will keep track of the current amount of moneythe dicethe number of rollsetc it will implement run method that we use to get things started and also some helper methods that are used to implement run we won' know exactly what methods are needed until we design the main algorithm up to this pointi have concentrated on the actual game that we are implementing another component to this program will be the user interface one good way to break down the complexity of more sophisticated program is to separate the user interface from the main guts of the program this is often called the model-view approach our program implements some model (in this caseit models poker game)and the interface is view of the current state of the model one way of separating out the interface is to encapsulate the decisions about the interface in separate interface object an advantage of this approach is that we can change the look and feel of the program simply by substituting different interface object for examplewe might have text-based version of program and graphical version let' assume that our program will make use of an interface objectcall it pokerinterface it' not clear yet exactly what behaviors we will need from this classbut as we refine the pokerapp classwe will need to get information from the user and also display information about the game these will correspond to methods implemented by the pokerinterface class
19,838
implementing the model so farwe have pretty good picture of what the dice class will do and starting point for implementing the pokerapp class we could proceed by working on either of these classes we won' really be able to try out the pokerapp class until we have diceso let' start with the lower-level dice class implementing dice the dice class implements collection of dicewhich are just changing numbers the obvious representation is to use list of five ints our constructor needs to create list and assign some initial values class dicedef __init__(self)self dice [ ]* self rollall(this code first creates list of five zeroes these need to be set to some random values since we are going to implement rollall function anywaycalling it here saves duplicating that code we need methods to roll selected dice and also to roll all of the dice since the latter is special case of the formerlet' turn our attention to the roll functionwhich rolls subset we can specify which dice to roll by passing list of indexes for exampleroll([ , , ]would roll the dice in positions and of the dice list we just need loop that goes through the parameter and generates new random value for each listed position def roll(selfwhich)for pos in whichself dice[posrandrange( , nextwe can use roll to implement rollall as followsdef rollall(self)self roll(range( ) used range( to generate sequence of all the indexes the values function is used to return the values of the dice so that they can be displayed another one-liner suffices def values(self)return self dice[:notice that created copy of the dice list by slicing it that wayif dice client modifies the list that it gets back from valuesit will not affect the original copy stored in the dice object this defensive programming prevents other parts of the code from accidentally messing with our object
19,839
finallywe come to the score method this is the function that will determine the worth of the current dice we need to examine the values and determine whether we have any of the patterns that lead to payoffnamelyfive of kindfour of kindfull housethree of kindtwo pairsor straight our function will need some way to indicate what the payoff is let' return string labeling what the hand is and an int that gives the payoff amount we can think of this function as multi-way decision we simply need to check for each possible hand if we do so in sensible orderwe can guarantee giving the correct payout for examplea full house also contains three of kind we need to check for the full house before checking for three of kindsince the full house is more valuable one simple way of checking the hand is to generate list of the counts of each value that iscounts[iwill be the number of times that the value occurs in dice if the dice are[ , , , , then the count list would be [ , , , , , , notice that counts[ will always be zerosince dice values are in the range - checking for various hands can then be done by looking for various values in counts for exampleif counts contains and the hand contains triple and pairhenceit is full house here' the codedef score(self)create the counts list counts [ for value in self dicecounts[valuecounts[value score the hand if in countsreturn "five of kind" elif in countsreturn "four of kind" elif ( in countsand ( in counts)return "full house" elif in countsreturn "three of kind" elif not ( in countsand (counts[ ]== or counts[ = )return "straight" elif counts count( = return "two pairs" elsereturn "garbage" the only tricky part is the testing for straights since we have already checked for and of kindchecking that there are no pairs--not in counts--guarantees that the dice show five distinct values if there is no then the values must be - likewiseno means the values must be -
19,840
at this pointwe could try out the dice class to make sure that it is working correctly here is short interaction showing some of what the class can dofrom dice import dice dice( values([ score(('two pairs' roll([ ] values([ roll([ ] values([ score(('full house' we would want to be sure that each kind of hand scores properly implementing pokerapp now we are ready to turn our attention to the task of actually implementing the poker game we can use top-down design to flesh out the details and also suggest what methods will have to be implemented in the pokerinterface class initiallywe know that the pokerapp will need to keep track of the dicethe amount of moneyand some user interface let' initialize these values in the constructor class pokerappdef __init__(self)self dice dice(self money self interface pokerinterface(to run the programwe will create an instance of this class and call its run method basicallythe program will loopallowing the user to continue playing hands until he or she is either out of money or chooses to quit since it costs $ to play handwe can continue as long as self money > determining whether the user actually wants to play another hand must come from the user interface here is one way we might code the run methoddef run(self)while self money > and self interface wanttoplay()self playround(self interface close(
19,841
notice the call to interface close at the bottom this will allow us to do any necessary cleaning up such as printing final message for the user or closing graphics window most of the work of the program has now been pushed into the playround method let' continue the top-down process by focusing our attention here each round will consist of series of rolls based on these rollsthe program will have to adjust the player' score def playround(self)self money self money self interface setmoney(self moneyself dorolls(resultscore self dice score(self interface showresult(resultscoreself money self money score self interface setmoney(self moneythis code only really handles the scoring aspect of round anytime new information must be shown to the usera suitable method from interface is invoked the $ fee to play round is first deducted and the interface is updated with the new amount of money remaining the program then processes series of rolls (dorolls)shows the user the resultand updates the amount of money accordingly finallywe are down to the nitty-gritty details of implementing the dice rolling process initiallyall of the dice will be rolled then we need loop that continues rolling user-selected dice until either the user chooses to quit rolling or the limit of three rolls is reached let' use local variable rolls to keep track of how many times the dice have been rolled obviouslydisplaying the dice and getting the list of dice to roll must come from interaction with the user through interface def dorolls(self)self dice rollall(roll self interface setdice(self dice values()toroll self interface choosedice(while roll and toroll ![]self dice roll(torollroll roll self interface setdice(self dice values()if roll toroll self interface choosedice(at this pointwe have completed the basic functions of our interactive poker program that iswe have model of the process for playing poker we can' really test out this program yethoweverbecause we don' have user interface
19,842
text-based ui in designing pokerapp we have also developed specification for generic pokerinterface class our interface must support the methods for displaying informationsetmoneysetdiceand showresult it must also have methods that allow for input from the userwanttoplayand choosedice these methods can be implemented in many different waysproducing programs that look quite different even though the underlying modelpokerappremains the same usuallygraphical interfaces are much more complicated to design and build than text-based ones if we are in hurry to get our application runningwe might first try building simple text-based interface we can use this for testing and debugging of the model without all the extra complication of full-blown gui firstlet' tweak our pokerapp class bit so that the user interface is supplied as parameter to the constructor class pokerappdef __init__(selfinterface)self dice dice(self money self interface interface then we can easily create versions of the poker program using different interfaces now let' consider bare-bones interface to test out the poker program our text-based version will not present finished applicationbut ratherit provides minimalist interface solely to get the program running each of the necessary methods can be given trivial implementation here is complete textinterface class using this approachtextpoker class textinterfacedef __init__(self)print("welcome to video poker "def setmoney(selfamt)print("you currently have ${ format(amt)def setdice(selfvalues)print("dice:"valuesdef wanttoplay(self)ans input("do you wish to try your luck"return ans[ in "yydef close(self)
19,843
print("\nthanks for playing!"def showresult(selfmsgscore)print("{ you win ${ format(msgscore)def choosedice(self)return eval(input("enter list of which to change ([to stop")using this interfacewe can test out our pokerapp program to see if we have implemented correct model here is complete program making use of the modules that we have developedtextpoker py -video dice poker using text-based interface from pokerapp import pokerapp from textpoker import textinterface inter textinterface(app pokerapp(interapp run(basicallyall this program does is create text-based interface and then build pokerapp using this interface and start it running instead of creating separate module for thiswe could also just add the necessary launching code at the end of our textpoker module when running this programwe get rough but usable interaction welcome to video poker do you wish to try your lucky you currently have $ dice[ enter list of which to change ([to stop[ , dice[ enter list of which to change ([to stop[ dice[ full house you win $ you currently have $ do you wish to try your lucky you currently have $ dice[ enter list of which to change ([to stop[ dice[ enter list of which to change ([to stop[full house you win $ you currently have $ do you wish to try your lucky
19,844
you currently have $ dice[ enter list of which to change ([to stop[ , dice[ enter list of which to change ([to stop[ , dice[ four of kind you win $ you currently have $ do you wish to try your luckn thanks for playingyou can see how this interface provides just enough so that we can test out the model in factwe've got game that' already quite bit of fun to playdeveloping gui now that we have working programlet' turn our attention to graphical interface our first step must be to decide exactly how we want our interface to look and function the interface will have to support the various methods found in the text-based version and will also probably have some additional helper methods designing the interaction let' start with the basic methods that must be supported and decide exactly how interaction with the user will occur clearlyin graphical interfacethe faces of the dice and the current score should be continuously displayed the setdice and setmoney methods will be used to change those displays that leaves one output methodshowresultthat we need to accommodate one common way to handle this sort of transient information is with message at the bottom of the window this is sometimes called status bar to get information from the userwe will make use of buttons in wanttoplaythe user will have to decide between either rolling the dice or quitting we could include "roll diceand "quitbuttons for this choice that leaves us with figuring out how the user should choose dice to implement choosedicewe could provide button for each die and have the user click the buttons for the dice they want to roll when the user is done choosing the dicethey could click the "roll dicebutton again to roll the selected dice elaborating on this ideait would be nice if we allowed the user to change his or her mind while selecting the dice perhaps clicking the button of currently selected die would cause it to become unselected the clicking of the button will serve as sort of toggle that selects/unselects particular die the user commits to certain selection by clicking on "roll dice our vision for choosedice suggests couple of tweaks for the interface firstwe should have some way of showing the user which dice are currently selected there are lots of ways we could do this one simple approach would be to change the color of the die let' "gray outthe pips on
19,845
object-oriented design the dice selected for rolling secondwe need good way for the user to indicate that they wish to stop rolling that isthey would like the dice scored just as they stand we could handle this by having them click the "roll dicebutton when no dice are selectedhence asking the program to roll no dice another approach would be to provide separate button to click that causes the dice to be scored the latter approach seems bit more intuitive/informative let' add "scorebutton to the interface now we have basic idea of how the interface will function we still need to figure out how it will look what is the exact layout of the widgetsfigure is sample of how the interface might look ' sure those of you with more artistic eye can come up with more pleasing interfacebut we'll use this one as our working design figure gui interface for video dice poker managing the widgets the graphical interface that we are developing makes use of buttons and dice our intent is to reuse the button and dieview classes for these widgets that were developed in previous the button class can be used as isand since we have quite number of buttons to managewe can use list of buttonssimilar to the approach we used in the calculator program from unlike the buttons in the calculator programthe buttons of our poker interface will not be active all of the time for examplethe dice buttons will only be active when the user is actually in the process of choosing dice when user input is requiredthe valid buttons for that interaction
19,846
will be set active and the others will be inactive to implement this behaviorwe can add helper method called choose to the pokerinterface class the choose method takes list of button labels as parameteractivates themand then waits for the user to click one of them the return value of the function is the label of the button that was clicked we can call the choose method whenever we need input from the user for exampleif we are waiting for the user to choose either the "roll diceor "quitbuttonwe would use sequence of code like thischoice self choose(["roll dice""quit"]if choice ="roll dice"assuming the buttons are stored in an instance variable called buttonshere is one possible implementation of choosedef choose(selfchoices)buttons self buttons activate choice buttonsdeactivate others for in buttonsif getlabel(in choicesb activate(elseb deactivate(get mouse clicks until an active button is clicked while truep self win getmouse(for in buttonsif clicked( )return getlabel(function exit here the other widgets in our interface will be our dieview that we developed in the last two basicallywe will use the same class as beforebut we need to add just bit of new functionality as discussed abovewe want to change the color of die to indicate whether it is selected for rerolling you might want to go back and review the dieview class rememberthe class constructor draws square and seven circles to represent the positions where the pips of various values will appear the setvalue method turns on the appropriate pips to display given value to refresh your memory bithere is the setvalue method as we left itdef setvalue(selfvalue)turn all the pips off for pip in self pips
19,847
pip setfill(self backgroundturn the appropriate pips back on for in self ontable[value]self pips[isetfill(self foregroundwe need to modify the dieview class by adding setcolor method this method will be used to change the color that is used for drawing the pips as you can see in the code for setvaluethe color of the pips is determined by the value of the instance variable foreground of coursechanging the value of foreground will not actually change the appearance of the die until it is redrawn using the new color the algorithm for setcolor seems straightforward we need two stepschange foreground to the new color redraw the current value of the die unfortunatelythe second step presents slight snag we already have code that draws valuenamely setvalue but setvalue requires us to send the value as parameterand the current version of dieview does not store this value anywhere once the proper pips have been turned onthe actual value is discarded in order to implement setcolorwe need to tweak setvalue so that it remembers the current value then setcolor can redraw the die using its current value the change to setvalue is easywe just need to add single line self value value this line stores the value parameter in an instance variable called value with the modified version of setvalueimplementing setcolor is breeze def setcolor(selfcolor)self foreground color self setvalue(self valuenotice how the last line simply calls setvalue to (re)draw the diepassing along the value that was saved from the last time setvalue was called creating the interface now that we have our widgets under controlwe are ready to actually implement our gui poker interface the constructor will create all of our widgetssetting up the interface for later interactions class graphicsinterfacedef __init__(self)self win graphwin("dice poker" self win setbackground("green "
19,848
banner text(point( , )"python poker parlor"banner setsize( banner setfill("yellow "banner setstyle("bold"banner draw(self winself msg text(point( , )"welcome to the dice table"self msg setsize( self msg draw(self winself createdice(point( , ) self buttons [self adddicebuttons(point( , ) button(self winpoint( ) "roll dice"self buttons append(bb button(self winpoint( ) "score"self buttons append(bb button(self winpoint( , ) "quit"self buttons append(bself money text(point( , )"$ "self money setsize( self money draw(self winyou should compare this code to figure to make sure you understand how the elements of the interface are created and positioned hope you noticed that pushed the creation of the dice and their associated buttons into couple of helper methods here are the necessary definitionsdef createdice(selfcentersize)center move(- *size, self dice [for in range( )view dieview(self wincentersizeself dice append(viewcenter move( *size, def adddicebuttons(selfcenterwidthheight)center move(- *width for in range( , )label "die { }format(ib button(self wincenterwidthheightlabelself buttons append(bcenter move( *width these two methods are similar in that they employ loop to draw five similar widgets in both casesa point variablecenteris used to calculate the correct position of the next widget
19,849
implementing the interaction you might be little scared at this point that the constructor for our gui interface was so complex even simple graphical interfaces involve many independent components getting them all set up and initialized is often the most tedious part of coding the interface now that we have that part out of the wayactually writing the code that handles the interaction will not be too hardprovided we attack it one piece at time let' start with the simple output methods setmoney and showresult these two methods display some text in our interface window since our constructor took care of creating and positioning the relevant text objectsall our methods have to do is call the settext methods for the appropriate objects def setmoney(selfamt)self money settext("${ }format(amt)def showresult(selfmsgscore)if score text "{ }you win ${ }format(msgscoreelsetext "you rolled { }format(msgself msg settext(textin similar spiritthe output method setdice must make call to the setvalue method of the appropriate dieview objects in dice we can do this with for loop def setdice(selfvalues)for in range( )self dice[isetvalue(values[ ]take good look at the line in the loop body it sets the ith die to show the ith value as you can seeonce the interface has been constructedmaking it functional is not overly difficult our output methods are completed with just few lines of code the input methods are only slightly more complicated the wanttoplay method will wait for the user to click either "roll diceor "quit we can use our choose helper method to do this def wanttoplay(self)ans self choose(["roll dice""quit"]self msg settext(""return ans ="roll diceafter waiting for the user to click an appropriate buttonthis method then clears out any message-such as the previous results--by setting the msg text to the empty string the method then returns boolean value by examining the label returned by choose
19,850
that brings us to the choosedice method here we must implement more extensive user interaction the choosedice method returns list of the indexes of the dice that the user wishes to roll in our guithe user will choose dice by clicking on corresponding buttons we need to maintain list of which dice have been chosen each time die button is clickedthat die is either chosen (its index is appended to the listor unchosen (its index is removed from the listin additionthe color of the corresponding dieview reflects the status of the die the interaction ends when the user clicks either the roll button or the score button if the roll button is clickedthe method returns the list of currently chosen indexes if the score button is clickedthe function returns an empty list to signal that the player is done rolling here is one way to implement the choosing of dice the comments in this code explain the algorithmdef choosedice(self)choices is list of the indexes of the selected dice choices [no dice chosen yet while truewait for user to click valid button self choose(["die ""die ""die ""die ""die ""roll dice""score"]if [ =" "user clicked die button eval( [ ] translate label to die index if in choicescurrently selectedunselect it choices remove(iself dice[isetcolor("black"elsecurrently unselectedselect it choices append(iself dice[isetcolor("gray"elseuser clicked roll or score for in self dicerevert appearance of all dice setcolor("black"if ="score"score clickedignore choices return [elif choices ![]don' accept roll unless some return choices dice are actually selected that about wraps up our program the only missing piece of our interface class is the close method to close up the graphical versionwe just need to close the graphics window def close(self)self win close(finallywe need few lines to actually get our graphical poker playing program started this
19,851
object-oriented design code is exactly like the start code for the textual versionexcept that we use graphicsinterface in place of the textinterface inter graphicsinterface(app pokerapp(interapp run(we now have completeusable video dice poker game of courseour game is lacking lot of bells and whistles such as printing nice introductionproviding help with the rulesand keeping track of high scores have tried to keep this example relatively simplewhile still illustrating important issues in the design of guis using objects improvements are left as exercises for you have fun with them oo concepts my goal for the racquetball and video poker case studies was to give you taste for what ood is all about actuallywhat you've seen is only distillation of the design process for these two programs basicallyi have walked you through the algorithms and rationale for two completed designs did not document every single decisionfalse startand detour along the way doing so would have at least tripled the size of this (already longyou will learn best by making your own decisions and discovering your own mistakesnot by reading about mine stillthese smallish examples illustrate much of the power and allure of the object-oriented approach hopefullyyou can see why oo techniques are becoming standard practice in software development the bottom line is that the oo approach helps us to produce complex software that is more reliable and cost-effective howeveri still have not defined exactly what counts as objected-oriented development most oo gurus talk about three features that together make development truly object-orientedencapsulationpolymorphismand inheritance don' want to belabor these concepts too muchbut your introduction to object-oriented design and programming would not be complete without at least some understanding of what is meant by these terms encapsulation have already mentioned the term encapsulation in previous discussion of objects as you knowobjects know stuff and do stuff they combine data and operations this process of packaging some data along with the set of operations that can be performed on the data is called encapsulation encapsulation is one of the major attractions of using objects it provides convenient way to compose complex solutions that corresponds to our intuitive view of how the world works we naturally think of the world around us as consisting of interacting objects each object has its own identityand knowing what kind of object it is allows us to understand its nature and capabilities look out my window and see housescarsand treesnot swarming mass of countless molecules or atoms
19,852
from design standpointencapsulation also provides critical service of separating the concerns of "whatvs "how the actual implementation of an object is independent of its use the implementation can changebut as long as the interface is preservedother components that rely on the object will not break encapsulation allows us to isolate major design decisionsespecially ones that are subject to change another advantage of encapsulation is that it supports code reuse it allows us to package up general components that can be used from one program to the next the dieview class and button classes are good examples of reusable components encapsulation is probably the chief benefit of using objectsbut alone it only makes system object-based to be truly objected-orientedthe approach must also have the characteristics of polymorphism and inheritance polymorphism literallythe word polymorphism means "many forms when used in object-oriented literaturethis refers to the fact that what an object does in response to message ( method calldepends on the type or class of the object our poker program illustrated one aspect of polymorphism the pokerapp class was used both with textinterface and graphicsinterface there were two different forms of interfaceand the pokerapp class could function quite well with either when the pokerapp called the showdice methodfor examplethe textinterface showed the dice one way and the graphicsinterface did it another way in our poker examplewe used either the text interface or the graphics interface the remarkable thing about polymorphismhoweveris that given line in program may invoke completely different method from one moment to the next as simple examplesuppose you had list of graphics objects to draw on the screen the list might contain mixture of circlerectanglepolygonetc you could draw all the items in list with this simple codefor obj in objectsobj draw(winnow ask yourselfwhat operation does this loop actually executewhen obj is circleit executes the draw method from the circle class when obj is rectangleit is the draw method from the rectangle classetc polymorphism gives object-oriented systems the flexibility for each object to perform an action just the way that it should be performed for that object before object orientationthis kind of flexibility was much harder to achieve inheritance the third important property for object-oriented approachesinheritanceis one that we have not yet used the idea behind inheritance is that new class can be defined to borrow behavior from another class the new class (the one doing the borrowingis called subclassand the existing class (the one being borrowed fromis its superclass
19,853
for exampleif we are building system to keep track of employeeswe might have class employee that contains the general information that is common to all employees one example attribute would be homeaddress method that returns the home address of an employee within the class of all employeeswe might distinguish between salariedemployee and hourlyemployee we could make these subclasses of employeeso they would share methods like homeaddress howevereach subclass would have its own monthlypay functionsince pay is computed differently for these different classes of employees inheritance provides two benefits one is that we can structure the classes of system to avoid duplication of operations we don' have to write separate homeaddress method for the hourlyemployee and salariedemployee classes closely related benefit is that new classes can often be based on existing classespromoting code reuse we could have used inheritance to build our poker program when we first wrote the dieview classit did not provide way of changing the appearance of the die we solved this problem by modifying the original class definition an alternative would have been to leave the original class unchanged and create new subclass colordieview colordieview is just like dieview except that it contains an additional method that allows us to change its color here is how it would look in pythonclass colordieview(dieview)def setvalue(selfvalue)self value value dieview setvalue(selfvaluedef setcolor(selfcolor)self foreground color self setvalue(self valuethe first line of this definition says that we are defining new class colordieview that is based on ( subclass ofdieview inside the new classwe define two methods the second methodsetcoloradds the new operation of coursein order to make setcolor workwe also need to modify the setvalue operation slightly the setvalue method in colordieview redefines or overrides the definition of setvalue that was provided in the dieview class the setvalue method in the new class first stores the value and then relies on the setvalue method of the superclass dieview to actually draw the pips notice especially how the call to the method from the superclass is made the normal approach self setvalue(valuewould refer to the setvalue method of the colordieview classsince self is an instance of colordieview in order to call the original setvalue method from the superclassit is necessary to put the class name where the object would normally go dieview setvalue(selfvaluethe actual object to which the method is applied is then sent as the first parameter
19,854
summary this has not introduced very much in the way of new technical content rather it has illustrated the process of object-oriented design through the racquetball simulation and dice poker case studies the key ideas of ood are summarized hereobject-oriented design (oodis the process of developing set of classes to solve problem it is similar to top-down design in that the goal is to develop set of black boxes and associated interfaces where top-down design looks for functionsood looks for objects there are many different ways to do ood the best way to learn is by doing it some intuitive guidelines can help look for object candidates identify instance variables think about interfaces refine nontrivial methods design iteratively try out alternatives keep it simple in developing programs with sophisticated user interfacesit' useful to separate the program into model and view components one advantage of this approach is that it allows the program to sport multiple looks ( text and gui interfacesthere are three fundamental principles that make software object orientedencapsulation separating the implementation details of an object from how the object is used this allows for modular design of complex programs polymorphism different classes may implement methods with the same signature this makes programs more flexibleallowing single line of code to call different methods in different situations inheritance new class can be derived from an existing class this supports sharing of methods among classes and code reuse exercises review questions true/false object-oriented design is the process of finding and defining useful set of functions for solving problem
19,855
candidate objects can be found by looking at the verbs in problem description typicallythe design process involves considerable trial-and-error guis are often built with model-view architecture hiding the details of an object in class definition is called instantiation polymorphism literally means "many changes superclass inherits behaviors from its subclasses guis are generally easier to write than text-based interfaces multiple choice which of the following was not class in the racquetball simulationaplayer bsimstats crballgame dscore what is the data type of server in an rballgameaint bplayer cbool dsimstats the isover method is defined in which classasimstats brballgame cplayer dpokerapp which of the following is not one of the fundamental characteristics of object-oriented design/programmingainheritance bpolymorphism cgenerality dencapsulation separating the user interface from the "gutsof an application is called (naabstract bobject-oriented cmodel-theoretic dmodel-view approach discussion in your own wordsdescribe the process of ood in your own wordsdefine encapsulationpolymorphismand inheritance programming exercises modify the dice poker program from this to include any or all of the following features(asplash screen when the program first fires uphave it print short introductory message about the program and buttons for "let' playand "exit the main interface shouldn' appear unless the user selects "let' play
19,856
(badd help button that pops up another window displaying the rules of the game (the payoffs table is the most important part(cadd high score feature the program should keep track of the best scores when user quits with good enough scorehe/she is invited to type in name for the list the list should be printed in the splash screen when the program first runs the high-scores list will have to be stored in file so that it persists between program invocations using the ideas from this implement simulation of another racquet game see the programming exercises from for some ideas write program to keep track of conference attendees for each attendeeyour program should keep track of namecompanystateand email address your program should allow users to do things such as add new attendeedisplay info on an attendeedelete an attendeelist the name and email addresses of all attendeesand list the name and email address of all attendees from given state the attendee list should be stored in file and loaded when the program starts write program that simulates an automatic teller machine (atmsince you probably don' have access to card readerhave the initial screen ask for user id and pin the user id will be used to look up the info for the user' accounts (including the pin to see if it matches what the user typeseach user will have access to checking account and savings account the user should able to check balanceswithdraw cashand transfer money between accounts design your interface to be similar to what you see on your local atm the user account information should be stored in file when the program terminates this file is read in again when the program restarts find the rules to an interesting dice game and write an interactive program to play it some examples are crapsyachtgreedand skunk write program that deals four bridge handscounts how many points they haveand gives opening bids you will probably need to consult beginner' guide to bridge to help you out find simple card game that you like and implement an interactive program to play that game some possibilities are warblackjackvarious solitaire gamesand crazy eights write an interactive program for board game some examples are othello(reversi)connect fourbattleshipsorry!and parcheesi
19,857
object-oriented design
19,858
algorithm design and recursion objectives to understand basic techniques for analyzing the efficiency of algorithms to know what searching is and understand the algorithms for linear and binary search to understand the basic principles of recursive definitions and functions and be able to write simple recursive functions to understand sorting in depth and know the algorithms for selection sort and merge sort to appreciate how the analysis of algorithms can demonstrate that some problems are intractable and others are unsolvable if you have worked your way through to this point in the bookyou are well on the way to becoming programmer way back in discussed the relationship between programming and the study of computer science now that you have some programming skillsyou are ready to start considering some broader issues in the field here we will take up one of the central issuesnamely the design and analysis of algorithms along the wayyou'll get glimpse of recursiona particularly powerful way of thinking about algorithms searching let' begin by considering very common and well-studied programming problemsearching searching is the process of looking for particular value in collection for examplea program that maintains the membership list for club might need to look up the information about particular member this involves some form of search process
19,859
algorithm design and recursion simple searching problem to make the discussion of searching algorithms as simple as possiblelet' boil the problem down to its essence here is the specification of simple searching functiondef search(xnums)nums is list of numbers and is number returns the position in the list where occurs or - if is not in the list here are couple interactive examples that illustrate its behaviorsearch( [ ] search( [ ]- in the first examplethe function returns the index where appears in the list in the second examplethe return value - indicates that is not in the list you may recall from our discussion of list operations that python actually provides number of built-in search-related methods for examplewe can test to see if value appears in sequence using in if in numsdo something if we want to know the position of in listthe index method fills the bill nicely nums [ , , , , nums index( in factthe only difference between our search function and index is that the latter raises an exception if the target value does not appear in the list we could implement search using index by simply catching the exception and returning - for that case def search(xnums)tryreturn nums index(xexceptreturn - this approach avoids the questionhowever the real issue is how does python actually search the listwhat is the algorithm
19,860
strategy linear search let' try our hand at developing search algorithm using simple "be the computerstrategy suppose that gave you page full of numbers in no particular order and asked whether the number is in the list how would you solve this problemif you are like most peopleyou would simply scan down the list comparing each value to when you see in the listyou quit and tell me that you found it if you get to the very end of the list without seeing then you tell me it' not there this strategy is called linear search you are searching through the list of items one by one until the target value is found this algorithm translates directly into simple code def search(xnums)for in range(len(nums))if nums[ =xitem foundreturn the index value return return - loop finisheditem was not in list this algorithm was not hard to developand it will work very nicely for modest-sized lists for an unordered listthis algorithm is as good as any the python in and index operations both implement linear searching algorithms if we have very large collection of datawe might want to organize it in some way so that we don' have to look at every single item to determine whereor ifa particular value appears in the list suppose that the list is stored in sorted order (lowest to highestas soon as we encounter value that is greater than the target valuewe can quit the linear search without looking at the rest of the list on averagethat saves us about half of the work butif the list is sortedwe can do even better than this strategy binary search when list is orderedthere is much better searching strategyone that you probably already know have you ever played the number guessing gamei pick number between and and you try to guess what it is each time you guessi will tell you if your guess is correcttoo highor too low what is your strategyif you play this game with very young childthey might well adopt strategy of simply guessing numbers at random an older child might employ systematic approach corresponding to linear searchguessing until the mystery value is found of coursevirtually any adult will first guess if told that the number is higherthen the range of possible values is - the next logical guess is each time we guess the middle of the remaining numbers to try to narrow down the possible range this strategy is called binary search binary means twoand at each stepwe are dividing the remaining numbers into two parts we can employ binary search strategy to look through sorted list the basic idea is that we use two variables to keep track of the endpoints of the range in the list where the item could be initiallythe target could be anywhere in the listso we start with variables low and high set to the first and last positions of the listrespectively
19,861
algorithm design and recursion the heart of the algorithm is loop that looks at the item in the middle of the remaining range to compare it to if is smaller than the middle itemthen we move highso that the search is narrowed to the lower half if is largerthen we move lowand the search is narrowed to the upper half the loop terminates when is found or there are no longer any more places to look ( low highhere is the codedef search(xnums)low high len(nums while low <highmid (low high)// item nums[midif =item return mid elif itemhigh mid elselow mid return - there is still range to search position of middle item found itreturn the index is in lower half of range move top marker down is in upper half move bottom marker up no range left to searchx is not there this algorithm is quite bit more sophisticated than the simple linear search you might want to trace through couple of example searches to convince yourself that it actually works comparing algorithms so farwe have developed two solutions to our simple searching problem which one is betterwellthat depends on what exactly we mean by better the linear search algorithm is much easier to understand and implement on the other handwe expect that the binary search is more efficientbecause it doesn' have to look at every value in the list intuitivelythenwe might expect the linear search to be better choice for small lists and binary search better choice for larger lists how could we actually confirm such intuitionsone approach would be to do an empirical test we could simply code up both algorithms and try them out on various sized lists to see how long the search takes these algorithms are both quite shortso it would not be difficult to run few experiments when tested the algorithms on my particular computer ( somewhat dated laptop)linear search was faster for lists of length or lessand there was not much noticeable difference in the range of length - after thatbinary search was clear winner for list of million elementslinear search averaged seconds to find random valuewhereas binary search averaged only seconds the empirical analysis has confirmed our intuitionbut these are results from one particular machine under specific circumstances (amount of memoryprocessor speedcurrent loadetc how can we be sure that the results will always be the sameanother approach is to analyze our algorithms abstractly to see how efficient they are other factors being equalwe expect the algorithm with the fewest number of "stepsto be the more
19,862
efficient but how do we count the number of stepsfor examplethe number of times that either algorithm goes through its main loop will depend on the particular inputs we have already guessed that the advantage of binary search increases as the size of the list increases computer scientists attack these problems by analyzing the number of steps that an algorithm will take relative to the size or difficulty of the specific problem instance being solved for searchingthe difficulty is determined by the size of the collection obviouslyit takes more steps to find number in collection of million than it does in collection of ten the pertinent question is how many steps are needed to find value in list of size we are particularly interested in what happens as gets very large let' consider the linear search first if we have list of ten itemsthe most work our algorithm might have to do is to look at each item in turn the loop will iterate at most ten times suppose the list is twice as big then we might have to look at twice as many items if the list is three times as largeit will take three times as longetc in generalthe amount of time required is linearly related to the size of the list this is what computer scientists call linear time algorithm now you really know why it' called linear search what about the binary searchlet' start by considering concrete example suppose the list contains sixteen items each time through the loopthe remaining range is cut in half after one passthere are eight items left to consider the next time through there will be fourthen twoand finally one how many times will the loop executeit depends on how many times we can halve the range before running out of data this table might help you to sort things outlist size halvings can you see the pattern hereeach extra iteration of the loop doubles the size of the list if the binary search loops timesit can find single value in list of size each time through the loopit looks at one value (the middlein the list to see how many items are examined in list of size nwe need to solve this relationshipn for in this formulai is just an exponent with base of using the appropriate logarithm gives us this relationshipi log if you are not entirely comfortable with logarithmsjust remember that this value is the number of times that collection of size can be cut in half okso what does this bit of math tell usbinary search is an example of log time algorithm the amount of time it takes to solve given problem grows as the log of the problem size in the case of binary searcheach additional iteration doubles the size of the problem that we can solve you might not appreciate just how efficient binary search really is let me try to put it in perspective suppose you have new york city phone book withsaytwelve million names listed in alphabetical order you walk up to typical new yorker on the street and make the following proposition (assuming their number is listed)" ' going to try guessing your name each time
19,863
algorithm design and recursion guess nameyou tell me if your name comes alphabetically before or after the name guess how many guesses will you needour analysis above shows the answer to this question is log if you don' have calculator handyhere is quick way to estimate the result or roughly and that means that that is is approximately one million sosearching million items requires only guesses continuing onwe need guesses for two million for four million for eight millionand guesses to search among sixteen million names we can figure out the name of total stranger in new york city using only guessesby comparisona linear search would require (on average million guesses binary search is phenomenally good algorithmi said earlier that python uses linear search algorithm to implement its built-in searching methods if binary search is so much betterwhy doesn' python use itthe reason is that the binary search is less generalin order to workthe list must be in order if you want to use binary search on an unordered listthe first thing you have to do is put it in order or sort it this is another well-studied problem in computer scienceand one that we should look at before we turn to sortinghoweverwe need to generalize the algorithm design technique that we used to develop the binary search recursive problem-solving rememberthe basic idea behind the binary search algorithm was to successively divide the problem in half this is sometimes referred to as "divide and conquerapproach to algorithm designand it often leads to very efficient algorithms one interesting aspect of divide and conquer algorithms is that the original problem divides into subproblems that are just smaller versions of the original to see what meanthink about the binary search again initiallythe range to search is the entire list our first step is to look at the middle item in the list should the middle item turn out to be the targetthen we are finished if it is not the targetwe continue by performing binary search on either the top-half or the bottom half of the list using this insightwe might express the binary search algorithm in another way algorithmbinarysearch -search for in nums[lownums[highmid (low high/ if low high is not in nums elif nums[midperform binary search for in nums[lownums[mid- else perform binary search for in nums[mid+ nums[highrather than using loopthis definition of the binary search seems to refer to itself what is going on herecan we actually make sense of such thing
19,864
recursive definitions description of something that refers to itself is called recursive definition in our last formulationthe binary search algorithm makes use of its own description "callto binary search "recursinside of the definition--hencethe label "recursive definition at first glanceyou might think recursive definitions are just nonsense surely you have had teacher who insisted that you can' use word inside its own definitionthat' called circular definition and is usually not worth much credit on an exam in mathematicshowevercertain recursive definitions are used all the time as long as we exercise some care in the formulation and use of recursive definitionsthey can be quite handy and surprisingly powerful the classic recursive example in mathematics is the definition of factorial back in we defined the factorial of value like thisnn( )( ( for examplewe can compute ( )( )( )( recall that we implemented program to compute factorials using simple loop that accumulates the factorial product looking at the calculation of !you will notice something interesting if we remove the from the frontwhat remains is calculation of in generalnn( )in factthis relation gives us another way of expressing what is meant by factorial in general here is recursive definitionn if ( )otherwise this definition says that the factorial of isby definition while the factorial of any other number is defined to be that number times the factorial of one less than that number even though this definition is recursiveit is not circular in factit provides very simple method of calculating factorial consider the value of by definition we have ( ) ( !but what is !to find outwe apply the definition again ( ! [( )( )! ( )( !nowof coursewe have to expand !which requires !which requires since is simply that' the end of it ( ! ( )( ! ( )( )( ! ( )( )( )( ! ( )( )( )( you can see that the recursive definition is not circular because each application causes us to request the factorial of smaller number eventually we get down to which doesn' require another application of the definition this is called base case for the recursion when the recursion bottoms outwe get closed expression that can be directly computed all good recursive definitions have these key characteristics
19,865
algorithm design and recursion there are one or more base cases for which no recursion is required all chains of recursion eventually end up at one of the base cases the simplest way to guarantee that these two conditions are met is to make sure that each recursion always occurs on smaller version of the original problem very small version of the problem that can be solved without recursion then becomes the base case this is exactly how the factorial definition works recursive functions you already know that the factorial can be computed using loop with an accumulator that implementation has natural correspondence to the original definition of factorial can we also implement version of factorial that follows the recursive definitionif we write factorial as separate functionthe recursive definition translates directly into code def fact( )if = return elsereturn fact( - do you see how the definition that refers to itself turns into function that calls itselfthis is called recursive function the function first checks to see if we are at the base case = andif soreturns if we are not yet at the base casethe function returns the result of multiplying by the factorial of - the latter is calculated by recursive call to fact( - think you will agree that this is reasonable translation of the recursive definition the really cool part is that it actually workswe can use this recursive function to compute factorial values from recfact import fact fact( fact( some beginning programmers are surprised by this resultbut it follows naturally from the semantics for functions that we discussed way back in remember that each call to function starts that function anew that means it has its own copy of any local valuesincluding the values of the parameters figure shows the sequence of recursive calls that computes note especially how each return value is multiplied by value of appropriate for each function invocation the values of are stored on the way down the chain and then used on the way back up as the function calls return there are many problems for which recursion can yield an elegant and efficient solution the next few sections present examples of recursive problem solving
19,866
= fact( def fact( )if = return elsereturn fact( - def fact( )if = nreturn elsereturn fact( - def fact( )if = return nelsereturn fact( - def fact( )if = return elsereturn fact( - def fact( )if = return else return fact( - = def fact( )if = return elsereturn fact( - figure recursive computation of examplestring reversal python lists have built-in method that can be used to reverse the list suppose that you want to compute the reverse of string one way to handle this problem effectively would be to convert the string into list of charactersreverse the listand turn the list back into string using recursionhoweverwe can easily write function that computes the reverse directlywithout having to detour through list representation the basic idea is to think of string as recursive objecta large string is composed out of smaller objectswhich are also strings in factone very handy way to divide up virtually any sequence is to think of it as single first item that just happens to be followed by another sequence in the case of stringwe can divide it up into its first character and "all the rest if we reverse the rest of the string and then put the first character on the end of thatwe'll have the reverse of the whole string let' code up that algorithm and see what happens def reverse( )return reverse( [ :] [ notice how this function works the slice [ :gives all but the first character of the string we reverse the slice (recursivelyand then concatenate the first character ( [ ]onto the end of the result it might be helpful to think in terms of specific example if is the string "abc"then [ :is the string "bcreversing this yields "cband tacking on [ yields "cbathat' just what we want unfortunatelythis function doesn' quite work here' what happens when try it outreverse("hello"
19,867
algorithm design and recursion traceback (most recent call last)file ""line in file ""line in reverse file ""line in reverse file ""line in reverse runtimeerrormaximum recursion depth exceeded 've only shown portion of the outputit actually consisted of lineswhat' happened hererememberto build correct recursive function we need base case for which no recursion is requiredotherwise the recursion is circular in our haste to code up the functionwe forgot to include base case what we have written is actually an infinite recursion every call to reverse contains another call to reverseso none of them ever return of courseeach time function is called it takes up some memory (to store the parameters and local variables)so this process can' go on forever python puts stop to it after callsthe default "maximum recursion depth let' go back and put in suitable base case when performing recursion on sequencesthe base case is often an empty sequence or sequence containing just one item for our reversing problem we can use an empty string as the base casesince an empty string is its own reverse the recursive calls to reverse are always on string that is one character shorter than the originalso we'll eventually end up at an empty string here' correct version of reversedef reverse( )if =""return elsereturn reverse( [ :] [ this version works as advertised reverse("hello"'ollehexampleanagrams an anagram is formed by rearranging the letters of word anagrams are often used in word gamesand forming anagrams is special case of generating the possible permutations (rearrangementsof sequencea problem that pops up frequently in many areas of computing and mathematics let' try our hand at writing function that generates list of all the possible anagrams of string we'll apply the same approach that we used in the previous example by slicing the first character off of the string suppose the original string is "abc"then the tail of the string is "bcgenerating the list of all the anagrams of the tail gives us ["bc""cb"]as there are only two possible arrangements of two characters to add back the first letterwe need to place it in all possible positions in each of these two smaller anagrams["abc""bac""bca""acb""cab""cba"the first three anagrams come from placing "ain every possible place in "bc"and the second three come from inserting "ainto "cb
19,868
just as in our previous examplewe can use an empty string as the base case for the recursion the only possible arrangement of characters in an empty string is the empty string itself here is the completed recursive functiondef anagrams( )if =""return [selseans [for in anagrams( [ :])for pos in range(len( )+ )ans append( [:pos]+ [ ]+ [pos:]return ans notice in the else have used list to accumulate the final results in the nested for loopsthe outer loop iterates through each anagram of the tail of sand the inner loop goes through each position in the anagram and creates new string with the original first character inserted into that position the expression [:pos]+ [ ]+ [pos:looks bit trickybut it' not too hard to decipher taking [:posgives the portion of up to (but not includingposand [pos:yields everything from pos through the end sticking [ between these two effectively inserts it into at pos the inner loop goes up to len( )+ so that the new character can be added to the very end of the anagram here is our function in actionanagrams("abc"['abc''bac''bca''acb''cab''cba' didn' use "hellofor this example because that generates more anagrams than wanted to print the number of anagrams of word is the factorial of the length of the word examplefast exponentiation another good example of recursion is clever algorithm for raising values to an integer power the naive way to compute an for an integer is simply to multiply by itself times an * * * we can easily implement this using simple accumulator loop def looppower(an)ans for in range( )ans ans return ans divide and conquer suggests another way to perform this calculation suppose we want to calculate by the laws of exponentswe know that ( so if we first calculate we can just do one more multiply to get to compute we can use the fact that ( and
19,869
of course ( putting the calculation together we start with ( and ( and ( we have calculated the value of using just three multiplications the basic insight is to use the relationship an an/ (an/ in the example gavethe exponents were all even in order to turn this idea into general algorithmwe also have to handle odd values of this can be done with one more multiplication for example ( )( here is the general relationshipn an// (an// if is even an// (an// )(aif is odd in this formula am exploiting integer divisionif is then // is we can use this relationship as the basis of recursive functionwe just need to find suitable base case notice that computing the nth power requires computing two smaller powers ( // if we keep using smaller and smaller values of nit will eventually get to ( // in integer divisionas you know from math classa for any value of (except there' our base case if you've followed all the maththe implementation of the function is straightforward def recpower(an)raises to the int power if = return elsefactor recpower(an// if % = is even return factor factor elsen is odd return factor factor one thing to notice is that used an intermediate variable factor so that an// only needs to be calculated once this makes the function more efficient examplebinary search now that you know how to implement recursive functionswe are ready to go back and look again at binary search recursively rememberthe basic idea was to look at the middle value and then recursively search either the lower half or the upper half of the array the base cases for the recursion are the conditions when we can stopnamelywhen the target value is found or we run out of places to look the recursive calls will cut the size of the problem in half each time in order to do thiswe need to specify the range of locations in the list that are still "in playfor each recursive call we can do this by passing the values of low and high as parameters along with the list each invocation will search the list between the low and high indexes here is direct implementation of the recursive algorithm using these ideasdef recbinsearch(xnumslowhigh)
19,870
if low highno place left to lookreturn - return - mid (low high/ item nums[midif item =xfound itreturn the index return mid elif itemlook in lower half return recbinsearch(xnumslowmid- elselook in upper half return recbinsearch(xnumsmid+ highwe can then implement our original search function using suitable call to the recursive binary searchtelling it to start the search between and len(nums)- def search(xnums)return recbinsearch(xnums len(nums)- of courseour original looping version is probably bit faster than this recursive version because calling functions is generally slower than iterating loop the recursive versionhowevermakes the divide-and-conquer structure of binary search much more obvious below we will see examples where recursive divide-and-conquer approaches provide natural solution to some problems where loops are awkward recursion vs iteration ' sure by now you've noticed that there are some similarities between iteration (loopingand recursion in factrecursive functions are generalization of loops anything that can be done with loop can also be done by simple kind of recursive function in factthere are programming languages that use recursion exclusively on the other handsome things that can be done very simply using recursion are quite difficult to do with loops for number of the problems we've looked at so farwe have had both iterative and recursive solutions in the case of factorial and binary searchthe loop version and the recursive version do basically the same calculationsand they will have roughly the same efficiency the looping versions are probably bit faster because calling functions is generally slower than iterating loopbut in modern language the recursive algorithms are probably fast enough in the case of the exponentiation algorithmthe recursive version and the looping version actually implement very different algorithms if you think about it bityou will see that the looping version is linear and the recursive version executes in log time the difference between these two is similar to the difference between linear search and binary searchso the recursive algorithm is clearly superior in the next sectionyou'll be introduced to recursive sorting algorithm that is also very efficient as you have seenrecursion can be very useful problem-solving technique that can lead to efficient and effective algorithms but you have to be careful it' also possible to write some very inefficient recursive algorithms one classic example is calculating the nth fibonacci number
19,871
the fibonacci sequence is the sequence of numbers it starts with two and successive numbers are the sum of the previous two one way to compute the nth fibonacci value is to use loop that produces successive terms of the sequence in order to compute the next fibonacci numberwe always need to keep track of the previous two we can use two variablescurr and prevto keep track these values then we just need loop that adds these together to get the next value at that pointthe old value of curr becomes the new value of prev here is one way to do it in pythondef loopfib( )returns the nth fibonacci number curr prev for in range( - )currprev curr+prevcurr return curr used simultaneous assignment to compute the next values of curr and prev in single step notice that the loop only goes around timesbecause the first two values have already been assigned and do not require an addition the fibonacci sequence also has an elegant recursive definition ib( if ib( ib( otherwise we can turn this recursive definition directly into recursive function def fib( )if return elsereturn fib( - fib( - this function obeys the rules that we've set out the recursion is always on smaller valuesand we have identified some non-recursive base cases thereforethis function will worksort of it turns out that this is horribly inefficient algorithm while our looping version can easily compute results for very large values of (loopfib( is almost instantaneous on my computer)the recursive version is useful only up to around the problem with this recursive formulation of the fibonacci function is that it performs lots of duplicate computations figure shows diagram of the computations that are performed to compute fib( notice that fib( is calculated twicefib( is calculated three timesfib( four timesetc if you start with larger numberyou can see how this redundancy really piles upso what does this tell usrecursion is just one more tool in your problem-solving arsenal sometimes recursive solution is good oneeither because it is more elegant or more efficient
19,872
fib( fib( fib( fib( fib( fib( fib( fib( fib( fib( fib( fib( fib( fib( fib( figure computations performed for fib( than looping versionin that case use recursion oftenthe looping and recursive versions are quite similarin that casethe edge probably goes to the loopas it will be slightly faster sometimes the recursive version is terribly inefficient in that caseavoid itunlessof courseyou can' come up with an iterative algorithm as you'll see later in the sometimes there just isn' good solution sorting algorithms the sorting problem provides nice test bed for the algorithm design techniques we have been discussing rememberthe basic sorting problem is to take list and rearrange it so that the values are in increasing (actuallynondecreasingorder naive sortingselection sort let' start with simple "be the computerapproach to sorting suppose you have stack of index cardseach with number on it the stack has been shuffledand you need to put the cards back in order how would you accomplish this taskthere are any number of good systematic approaches one simple method is to look through the deck to find the smallest value and then place that value at the front of the stack (or perhaps in separate stackthen you could go through and find the smallest of the remaining cards and put it next in lineetc of coursethis means that you'll also need an algorithm for finding the smallest remaining value you can use the same approach we used for finding the max of list (see as you go throughyou keep track of the smallest value seen so farupdating that value whenever you find smaller one the algorithm just described is called selection sort basicallythe algorithm consists of loop
19,873
and each time through the loopwe select the smallest of the remaining elements and move it into its proper position applying this idea to list of elementswe proceed by finding the smallest value in the list and putting it into the th position then we find the smallest remaining value (from positions -( - )and put it in position nextthe smallest value from positions -( - goes into position etc when we get to the end of the listeverything will be in its proper place there is one subtlety in implementing this algorithm when we place value into its proper positionwe need to make sure that we do not accidentally lose the value that was originally stored in that position for exampleif the smallest item is in position moving it into position involves an assignment nums[ nums[ but this wipes out the value currently in nums[ ]it really needs to be moved to another location in the list simple way to save the value is to swap it with the one that we are moving using simultaneous assignmentthe statement nums[ ]nums[ nums[ ]nums[ places the value from position at the front of the listbut preserves the original first value by stashing it into location using this ideait is simple matter to write selection sort in python will use variable called bottom to keep track of which position in the list we are currently fillingand the variable mp will be used to track the location of the smallest remaining value the comments in this code explain this implementation of selection sortdef selsort(nums)sort nums into ascending order len(numsfor each position in the list (except the very lastfor bottom in range( - )find the smallest item in nums[bottomnums[ - mp bottom for in range(bottom+ , )if nums[inums[mp]mp bottom is smallest initially look at each position this one is smaller remember its index swap smallest item to the bottom nums[bottom]nums[mpnums[mp]nums[bottomone thing to notice about this algorithm is the accumulator for finding the minimum value rather than actually storing the minimum seen so farmp just remembers the position of the minimum new value is tested by comparing the item in position to the item in position mp you should also
19,874
notice that bottom stops at the second to last item in the list once all of the items up to the last have been put in the proper placethe last item has to be the largestso there is no need to bother looking at it the selection sort algorithm is easy to write and works well for moderate-sized listsbut it is not very efficient sorting algorithm we'll come back and analyze it after we've developed another algorithm divide and conquermerge sort as discussed aboveone technique that often works for developing efficient algorithms is the divideand-conquer approach suppose friend and were working together trying to put our deck of cards in order we could divide the problem up by splitting the deck of cards in half with one of us sorting each of the halves then we just need to figure out way of combining the two sorted stacks the process of combining two sorted lists into single sorted result is called merging the basic outline of our divide and conquer algorithmcalled mergesort looks like thisalgorithmmergesort nums split nums into two halves sort the first half sort the second half merge the two sorted halves back into nums the first step in the algorithm is simplewe can just use list slicing to handle that the last step is to merge the lists together if you think about itmerging is pretty simple let' go back to our card stack example to flesh out the details since our two stacks are sortedeach has its smallest value on top whichever of the top values is the smallest will be the first item in the merged list once the smaller value is removedwe can look at the tops of the stacks againand whichever top card is smaller will be the next item in the list we just continue this process of placing the smaller of the two top values into the big list until one of the stacks runs out at that pointwe finish out the list with the cards from the remaining stack here is python implementation of the merge process in this codelst and lst are the smaller lists and lst is the larger list where the results are placed in order for the merging process to workthe length of lst must be equal to the sum of the lengths of lst and lst you should be able to follow this code by studying the accompanying commentsdef merge(lst lst lst )merge sorted lists lst and lst into lst these indexes keep track of current position in each list all start at the front len(lst )len(lst
19,875
algorithm design and recursion loop while both lst and lst have more items while and if lst [ lst [ ]top of lst is smaller lst [ lst [ copy it into current spot in lst elsetop of lst is smaller lst [ lst [ copy it into current spot in lst item added to lst update position here either lst or lst is done one of the following loops will execute to finish up the merge copy remaining items (if anyfrom lst while lst [ lst [ copy remaining items (if anyfrom lst while lst [ lst [ oknow we can slice list into twoand if those lists are sortedwe know how to merge them back into single list but how are we going to sort the smaller listswelllet' think about it we are trying to sort listand our algorithm requires us to sort two smaller lists this sounds like perfect place to use recursion maybe we can use mergesort itself to sort the two lists let' go back to our recursion guidelines to develop proper recursive algorithm in order for recursion to workwe need to find at least one base case that does not require recursive calland we also have to make sure that recursive calls are always made on smaller versions of the original problem the recursion in our mergesort will always occur on list that is half as large as the originalso the latter property is automatically met eventuallyour lists will be very smallcontaining only single item fortunatelya list with just one item is already sortedvoilawe have base case when the length of the list is less than we do nothingleaving the list unchanged given our analysiswe can update the mergesort algorithm to make it properly recursive if len(nums split nums into two halves mergesort the first half mergesort the second half merge the two sorted halves back into nums
19,876
we can translate this algorithm directly into python code def mergesort(nums)put items of nums in ascending order len(numsdo nothing if nums contains or items if split into two sublists / nums nums nums[: ]nums[ :recursively sort each piece mergesort(nums mergesort(nums merge the sorted pieces back into original list merge(nums nums numsyou might try tracing this algorithm with small list (say eight elements)just to convince yourself that it really works in generalthoughtracing through recursive algorithms can be tedious and often not very enlightening recursion is closely related to mathematical inductionand it requires practice before it becomes comfortable as long as you follow the rules and make sure that every recursive chain of calls eventually reaches base caseyour algorithms will work you just have to trust and let go of the grungy details let python worry about that for youcomparing sorts now that we have developed two sorting algorithmswhich one should we usebefore we actually try them outlet' do some analysis as in the searching problemthe difficulty of sorting list depends on the size of the list we need to figure out how many steps each of our sorting algorithms requires as function of the size of the list to be sorted take look back at the algorithm for selection sort rememberthis algorithm works by first finding the smallest itemthen finding the smallest of the remaining itemsand so on suppose we start with list of size in order to find the smallest valuethe algorithm has to inspect each of the items the next time around the outer loopit has to find the smallest of the remaining items the third time aroundthere are items of interest this process continues until there is only one item left to place thusthe total number of iterations of the inner loop for the selection sort can be computed as the sum of decreasing sequence ( ( ( in other wordsthe time required by selection sort to sort list of items is proportional to the sum of the first whole numbers there is well-known formula for this sumbut even if you do not know the formulait is easy to derive if you add the first and last numbers in the series you get adding the second and second to last values gives ( if you keep pairing
19,877
up the values working from the outside inall of the pairs add to since there are numbersthere must be pairs that means the sum of all the pairs is ( + you can see that the final formula contains an term that means that the number of steps in the algorithm is proportional to the square of the size of the list if the size of the list doublesthe number of steps quadruples if the size triplesit will take nine times as long to finish computer scientists call this quadratic or algorithm let' see how that compares to the merge sort algorithm in the case of merge sortwe divided list into two pieces and sorted the individual pieces before merging them together the real work is done during the merge process when the values in the sublists are copied back into the original list figure depicts the merging process to sort the list [ the dashed lines show how the original list is continually halved until each item is its own list with the values shown at the bottom the single-item lists are then merged back up into the two item lists to produce the values shown in the second level the merging process continues up the diagram to produce the final sorted version of the list shown at the top figure merges required to sort [ the diagram makes analysis of the merge sort easy starting at the bottom levelwe have to copy the values into the second level from the second to third levelthe values need to be copied again each level of merging involves copying values the only question left to answer is how many levels are therethis boils down to how many times list of size can be split in half you already know from the analysis of binary search that this is just log thereforethe total work required to sort items is log computer scientists call this an log algorithm so which is going to be betterthe selection sort or the log merge sortif the input size is smallthe selection sort might be little faster because the code is simpler and there is less overhead what happensthough as gets largerwe saw in the analysis of binary search that the log function grows very slowly (log so (log nwill grow much slower than
19,878
'selsort'mergesort seconds list size figure experimental comparison of selection sort and merge sort (nempirical testing of these two algorithms confirms this analysis on my computerselection sort beats merge sort on lists up to size about which takes around seconds on larger liststhe merge sort dominates figure shows comparison of the time required to sort lists up to size you can see that the curve for selection sort veers rapidly upward (forming half of parabola)while the merge sort curve looks almost straight (look at the bottomfor itemsselection sort requires over seconds while merge sort completes the task in about of second merge sort can sort list of , items in less than six secondsselection sort takes around minutes that' quite difference hard problems using our divide-and-conquer approach we were able to design good algorithms for the searching and sorting problems divide and conquer and recursion are very powerful techniques for algorithm design howevernot all problems have efficient solutions
19,879
algorithm design and recursion towers of hanoi one very elegant application of recursive problem solving is the solution to mathematical puzzle usually called the tower of hanoi or tower of brahma this puzzle is generally attributed to the french mathematician edouard lucaswho published an article about it in the legend surrounding the puzzle goes something like thissomewhere in remote region of the world is monastery of very devout religious order the monks have been charged with sacred task that keeps time for the universe at the beginning of all thingsthe monks were given table that supports three vertical posts on one of the posts was stack of concentric golden disks the disks are of varying radii and stacked in the shape of beautiful pyramid the monks were charged with the task of moving the disks from the first post to the third post when the monks have completed their taskall things will crumble to dust and the universe will end of courseif that' all there were to the problemthe universe would have ended long ago to maintain divine orderthe monks must abide by certain rules only one disk may be moved at time disk may not be "set aside it may only be stacked on one of the three posts larger disk may never be placed on top of smaller one versions of this puzzle were quite popular at one timeand you can still find variations on this theme in toy and puzzle stores figure depicts small version containing only eight disks the task is to move the tower from the first post to the third post using the center post as sort of temporary resting place during the process of courseyou have to follow the three sacred rules given above we want to develop an algorithm for this puzzle you can think of our algorithm either as set of steps that the monks need to carry outor as program that generates set of instructions for exampleif we label the three posts aband the instructions might start out like thismove disk from to move disk from to move disk from to this is difficult puzzle for most people to solve of coursethat is not surprisingsince most people are not trained in algorithm design the solution process is actually quite simple--if you know about recursion let' start by considering some really easy cases suppose we have version of the puzzle with only one disk moving tower consisting of single disk is simple enoughwe just remove it from and put it on problem solved okwhat if there are two disksi need to get the larger of the two disks over to post cbut the smaller one is sitting on top of it need to move the smaller disk out of the wayand can do this by moving it to post now the large disk on is cleari can move it to and then move the smaller disk from post onto post
19,880
figure tower of hanoi puzzle with eight disks now let' think about tower of size three in order to move the largest disk to post ci first have to move the two smaller disks out of the way the two smaller disks form tower of size two using the process outlined abovei could move this tower of two onto post band that would free up the largest disk so that can move it to post then just have to move the tower of two disks from post onto post solving the three disk case boils down to three steps move tower of two from to move one disk from to move tower of two from to the first and third steps involve moving tower of size two fortunatelywe have already figured out how to do this it' just like solving the puzzle with two disksexcept that we move the tower from to using as the temporary resting placeand then from to using as the temporary we have just developed the outline of simple recursive algorithm for the general process of moving tower of any size from one post to another algorithmmove -disk tower from source to destination via resting place move - disk tower from source to resting place move disk tower from source to destination move - disk tower from resting place to destination what is the base case for this recursive processnotice how move of disks results in two recursive moves of disks since we are reducing by one each timethe size of the tower
19,881
algorithm design and recursion will eventually be tower of size can be moved directly by just moving single diskwe don' need any recursive calls to remove disks above it fixing up our general algorithm to include the base case gives us working movetower algorithm let' code it up in python our movetower function will need parameters to represent the size of the towernthe source postsourcethe destination postdestand the temporary resting posttemp we can use an int for and the strings " ," ,and "cto represent the posts here is the code for movetowerdef movetower(nsourcedesttemp)if = print("move disk from"source"to"dest+"elsemovetower( - sourcetempdestmovetower( sourcedesttempmovetower( - tempdestsourcesee how easy that wassometimes using recursion can make otherwise difficult problems almost trivial to get things startedwe just need to supply values for our four parameters let' write little function that prints out instructions for moving tower of size from post to post def hanoi( )movetower( " "" "" "now we're ready to try it out here are solutions to the threeand four-disk puzzles you might want to trace through these solutions to convince yourself that they work hanoi( move disk from to move disk from to move disk from to move disk from to move disk from to move disk from to move disk from to hanoi( move disk from to move disk from to move disk from to move disk from to move disk from to move disk from to move disk from to
19,882
move disk from to move disk from to move disk from to move disk from to move disk from to move disk from to move disk from to move disk from to soour solution to the tower of hanoi is "trivialalgorithm requiring only nine lines of code what is this problem doing in section labeled hard problemsto answer that questionwe have to look at the efficiency of our solution rememberwhen talk about the efficiency of an algorithm mean how many steps it requires to solve given size problem in this casethe difficulty is determined by the number of disks in the tower the question we want to answer is how many steps does it take to move tower of size njust looking at the structure of our algorithmyou can see that moving tower of size requires us to move tower of size twiceonce to move it off the largest diskand again to put it back on top if we add another disk to the towerwe essentially double the number of steps required to solve it the relationship becomes clear if you simply try out the program on increasing puzzle sizes number of disks steps in solution in generalsolving puzzle of size will require steps computer scientists call this an exponential time algorithmsince the measure of the size of the problemnappears in the exponent of this formula exponential algorithms blow up very quickly and can only be practically solved for relatively small sizeseven on the fastest computers just to illustrate the pointif our monks really started with tower of just disks and moved one disk every second hours dayevery daywithout making mistakeit would still take them over billion years to complete their task considering that the universe is roughly billion years old nowi' not too worried about turning to dust just yet even though the algorithm for towers of hanoi is easy to expressit belongs to class known as intractable problems these are problems that require too much computing power (either time or memoryto be solved in practiceexcept for the simplest cases and in this senseour toy-store puzzle does indeed represent hard problem but some problems are even harder than intractableand we'll meet one of those in the next section
19,883
algorithm design and recursion the halting problem let' just imagine for moment that this book has inspired you to pursue career as computer professional it' now six years laterand you are well-established software developer one dayyour boss comes to you with an important new projectand you are supposed to drop everything and get right on it it seems that your boss has had sudden inspiration on how your company can double its productivity you've recently hired number of rather inexperienced programmersand debugging their code is taking an inordinate amount of time apparentlythese wet-behind-the-ears newbies tend to accidentally write lot of programs with infinite loops (you've been thereright?they spend half the day waiting for their computers to reboot so they can track down the bugs your boss wants you to design program that can analyze source code and detect whether it contains an infinite loop before actually running it on test data this sounds like an interesting problemso you decide to give it try as usualyou start by carefully considering the specifications basicallyyou want program that can read other programs and determine whether they contain an infinite loop of coursethe behavior of program is determined not just by its codebut also by the input it is given when it runs in order to determine if there is an infinite loopyou will have to know what the input will be you decide on the following specificationprogramhalting analyzer inputsa python program file the input for the program outputs"okif the program will eventually stop "faultyif the program has an infinite loop right away you notice something interesting about this program this is program that examines other programs you may not have written many of these beforebut you know that it' not problem in principle after allcompilers and interpreters are common examples of programs that analyze other programs you can represent both the program that is being analyzed and the proposed input to the program as python strings there is something else very interesting about this assignment you are being asked to solve very famous puzzle known and the halting problemand it' unsolvable there is no possible algorithm that can meet this specificationnoticei' not just saying that no one has been able to do this beforei' saying that this problem can never be solvedin principle how do know that there is no solution to this problemthis is question that all the design skills in the world will not answer design can show that problems are solvablebut it can never prove that problem is not solvable to do thatwe need to use our analytical skills one way to prove that something is impossible is to first assume that it is possible and show that this leads to contradiction mathematicians call this proof by contradiction we'll use this technique to show that the halting problem cannot be solved
19,884
we begin by assuming that there is some algorithm that can determine if any program terminates when executed on particular input if such an algorithm could be writtenwe could package it up in function def terminates(programinputdata)program and inputdata are both strings returns true if program would halt when run with inputdata as its input of coursei can' actually write the functionbut let' just assume that this function exists using the terminates functionwe can write an interesting program turing py def terminates(programinputdata)program and inputdata are both strings returns true if program would halt when run with inputdata as its input def main()read program from standard input lines [print("type in program (type 'doneto quit"line input(""while line !"done"lines append(lineline input(""testprog "\njoin(linesif program halts on itself as inputgo into an infinite loop if terminates(testprogtestprog)while truepass pass statement does nothing main( have called this program turing in honor of alan turingthe british mathematician considered by many to be the "father of computer science he was the one who first proved that the halting problem could not be solved the first thing turing py does is read in program typed by the user this is accomplished with sentinel loop that accumulates lines in list one at time the join method then concatenates the lines together using newline character ("\ "between them this effectively creates multi-line string representing the program that was typed turing py then calls the terminates function and sends the input program as both the program to test and the input data for the program essentiallythis is test to see if the program read from
19,885
algorithm design and recursion the input terminates when given itself as input the pass statement actually does nothingif the terminates function returns trueturing py will go into an infinite loop okthis seems like silly programbut there is nothing in principle that keeps us from writing itprovided that the terminates function exists turing py is constructed in this peculiar way simply to illustrate point here' the million dollar questionwhat happens if we run turing py andwhen prompted to type in programtype in the contents of turing py itselfput more specificallydoes turing py halt when given itself as its inputlet' think it through we are running turing py and providing turing py as its input in the call to terminatesboth the program and the data will be copy of turing pyso if turing py halts when given itself as inputterminates will return true but if terminates returns trueturing py then goes into an infinite loopso it doesn' haltthat' contradictionturing py can' both halt and not halt it' got to be one or the other let' try it the other way around suppose that terminates returns false value that means that turing pywhen given itself as input goes into an infinite loop but as soon as terminates returns falseturing py quitsso it does haltit' still contradiction if you've gotten your head around the previous two paragraphsyou should be convinced that turing py represents an impossible program the existence of function meeting the specification for terminates leads to logical impossibility thereforewe can safely conclude that no such function exists that means that there cannot be an algorithm for solving the halting problem there you have it your boss has assigned you an impossible task fortunatelyyour knowledge of computer science is sufficient to recognize this you can explain to your boss why the problem can' be solved and then move on to more productive pursuits conclusion hope this has given you taste of what computer science is all about as the examples in this have showncomputer science is much more than "justprogramming the most important computer for any computing professional is still the one between the ears hopefully this book has helped you along the road to becoming computer programmer along the wayi have tried to pique your curiosity about the science of computing if you have mastered the concepts in this textyou can already write interesting and useful programs you should also have firm foundation of the fundamental ideas of computer science and software engineering should you be interested in studying these fields in more depthi can only say "go for it perhaps one day you will also consider yourself computer scientisti would be delighted if my book played even very small part in that process summary this has introduced you to number of important concepts in computer science that go beyond just programming here are the key ideasone core subfield of computer science is analysis of algorithms computer scientists analyze
19,886
the time efficiency of an algorithm by considering how many steps the algorithm requires as function of the input size searching is the process of finding particular item among collection linear search scans the collection from start to end and requires time linearly proportional to the size of the collection if the collection is sortedit can be searched using the binary search algorithm binary search only requires time proportional to the log of the collection size binary search is an example of divide and conquer approach to algorithm development divide and conquer often yields efficient solutions definition or function is recursive if it refers to itself to be well-foundeda recursive definition must meet two properties there must be one or more base cases that require no recursion all chains of recursion must eventually reach base case simple way to guarantee these conditions is for recursive calls to always be made on smaller versions of the problem the base cases are then simple versions that can be solved directly sequences can be considered recursive structures containing first item followed by sequence recursive functions can be written following this approach recursion is more general than iteration choosing between recursion and looping involves the considerations of efficiency and elegance sorting is the process of placing collection in order selection sort requires time proportional to the square of the size of the collection merge sort is divide and conquer algorithm that can sort collection in log time problems that are solvable in theory but not in practice are called intractable the solution to the famous towers of hanoi can be expressed as simple recursive algorithmbut the algorithm is intractable some problems are in principle unsolvable the halting problem is one example of an unsolvable problem you should consider becoming computer scientist exercises review questions true/false linear search requires number of steps proportional to the size of the list being searched
19,887
algorithm design and recursion the python operator in performs binary search binary search is an log algorithm the number of times can be divided by is exp( all proper recursive definitions must have exactly one non-recursive base case sequence can be viewed as recursive data collection word of length has nanagrams loops are more general than recursion merge sort is an example of an log algorithm exponential algorithms are generally considered intractable multiple choice which algorithm requires time directly proportional to the size of the inputalinear search bbinary search cmerge sort dselection sort approximately how many iterations will binary search need to find value in list of itemsa recursions on sequences often use this as base casea can empty sequence dnone an infinite recursion will result in aa program that "hangsba broken computer ca reboot da run-time exception the recursive fibonacci function is inefficient because ait does many repeated computations brecursion is inherently inefficient compared to iteration ccalculating fibonacci numbers is intractable dfibbing is morally wrong which is quadratic time algorithmalinear search bbinary search ctower of hanoi dselection sort
19,888
the process of combining two sorted sequences is called asorting bshuffling cdovetailing dmerging recursion is related to the mathematical technique called alooping bsequencing cinduction dcontradiction how many steps would be needed to solve the towers of hanoi for tower of size which of the following is not true of the halting problemait was studied by alan turing bit is harder than intractable csomeday clever algorithm may be found to solve it dit involves program that analyzes other programs discussion place these algorithm classes in order from fastest to slowestn log nnn log in your own wordsexplain the two rules that proper recursive definition or function must follow what is the exact result of anagram("foo") trace recpower( , and figure out exactly how many multiplications it performs why are divide-and-conquer algorithms often very efficientprogramming exercises modify the recursive fibonacci program given in the so that it prints tracing information specificallyhave the function print message when it is called and when it returns for examplethe output should contain lines like thesecomputing fib( leaving fib( returning use your modified version of fib to compute fib( and count how many times fib( is computed in the process this exercise is another variation on "instrumentingthe recursive fibonacci program to better understand its behavior write program that counts how many times the fib function is called to compute fib(nwhere is user input hintto solve this problemyou need an accumulator variable whose value "persistsbetween calls to fib you can do this by making the count an instance variable of an object create fibcounter class with the following methods
19,889
__init__(selfcreates new fibcounter setting its count instance variable to getcount(selfreturns the value of count fib(self,nrecursive function to compute the nth fibonacci number it increments the count each time it is called resetcount(selfset the count back to palindrome is sentence that contains the same sequence of letters reading it either forwards or backwards classic example is"able was iere saw elba write recursive function that detects whether string is palindrome the basic idea is to check that the first and last letters of the string are the same letterif they arethen the entire string is palindrome if everything between those letters is palindrome there are couple of special cases to check for if either the first or last character of the string is not letteryou can check to see if the rest of the string is palindrome with that character removed alsowhen you compare lettersmake sure that you do it in case-insensitive way use your function in program that prompts user for phrase and then tells whether or not it is palindrome here' another classic for testing" mana plana canalpanama! write and test recursive function max to find the largest number in list the max is the larger of the first item and the max of all the other items computer scientists and mathematicians often use numbering systems other than base write program that allows user to enter number and base and then prints out the digits of the number in the new base use recursive function baseconversion(num,baseto print the digits hintconsider base to get the rightmost digit of base numbersimply look at the remainder after dividing by for example % is to get the remaining digitsyou repeat the process on which is just / this same process works for any base the only problem is that we get the digits in reverse order (right to leftwrite recursive function that first prints the digits of num//base and then prints the last digitnamely num%base you should put space between successive digitssince bases greater than will print out with multi-character digits for examplebaseconversion( should print write recursive function to print out the digits of number in english for exampleif the number is the output should be "one five three see the hint from the previous problem for help on how this might be done in mathematicsckn denotes the number of different ways that things can be selected from among different choices for exampleif you are choosing among six desserts and are allowed to take twothe number of different combinations you could choose is here' one formula to compute this valueckn nk!( )
19,890
this value also gives rise to an interesting recursionn- ckn ck- ckn- write both an iterative and recursive function to compute combinations and compare the efficiency of your two solutions hintswhen ckn and when kckn some interesting geometric curves can be described recursively one famous example is the koch curve it is curve that can be infinitely long in finite amount of space it can also be used to generate pretty pictures the koch curve is described in terms of "levelsor "degrees the koch curve of degree is just straight line segment first degree curve is formed by placing "bumpin the middle of the line segment (see figure the original segment has been divided into foureach of which is / the length of the original the bump rises at degreesso it forms two sides of an equilateral triangle to get second degree curveyou put bump in each of the line segments of the first degree curve successive curves are constructed by placing bumps on each segment of the previous curve figure koch curves of degree to you can draw interesting pictures by "kochizingthe sides of polygon figure shows the result of applying fourth degree curve to the sides of an equilateral triangle this is often called "koch snowflake you are to write program to draw snowflake hintsthink of drawing koch curve as if you were giving instructions to turtle the turtle always knows where it currently sits and what direction it is facing to draw koch curve of given length and degreeyou might use an algorithm like thisalgorithm koch(turtlelengthdegree)if degree =
19,891
algorithm design and recursion figure koch snowflake tell the turtle to draw for length steps elselength length/ degree degree- koch(turtlelength degree tell the turtle to turn left degrees koch(turtlelength degree tell the turtle to turn right degrees koch(turtlelength degree tell the turtle to turn left degrees koch(turtlelength degree implement this algorithm with turtle class that contains instance variables location ( pointand direction ( floatand methods such as moveto(somepoint)draw(length)and turn(degreesif you maintain direction as an angle in radiansthe point you are going to can easily be computed from your current location just use dx length cos(directionand dy length sin(direction another interesting recursive curve (see previous problemis the -curve it is formed similarly to the koch curve except whereas the koch curve breaks segment into four pieces of length/ the -curve replaces each segment with just two segments of length that form degree elbow figure shows degree -curve using an approach similar to the previous exercisewrite program that draws -curve hintyour turtle will do the following
19,892
figure -curve of degree turn left degrees draw -curve of size length/sqrt( turn right degrees draw -curve of size length/sqrt( turn left degrees automated spell checkers are used to analyze documents and locate words that might be misspelled these programs work by comparing each word in the document to large dictionary (in the non-python senseof words if the word is not found in the dictionaryit is flagged as potentially incorrect write program to perform spell-checking on text file to do thisyou will need to get large file of english words in alphabetical order if you have unix or linux system availableyou might poke around for file called wordsusually located in /usr/dict or /usr/share/dict otherwisea quick search on the internet should turn up something usable your program should prompt for file to analyze and then try to look up every word in the file using binary search if word is not found in the dictionaryprint it on the screen as potentially incorrect write program that solves word jumble problems you will need large dictionary of english words (see previous problemthe user types in scrambled wordand your program
19,893
algorithm design and recursion generates all anagrams of the word and then checks which (if anyare in the dictionary the anagrams appearing in the dictionary are printed as solutions to the puzzle
19,894
__doc__ __init__ __name__ abstraction accessor accumulator acronym addinterest py addinterest py addinterest py algorithm analysis definition of design strategy divide and conquer exponential time intractable linear time log time quadratic ( -squaredtime algorithms average numbers counted loop empty string sentinel interactive loop binary search cannonball simulation future value future value graph input validation linear search max-of-three comparing each to all decision tree sequential median merge sort message decoding message encoding quadratic equation three-way decision racquetball simulation simonegame selection sort simngames temperature conversion alias anagrams recursive function analysis software development analysis of algorithms and operational definition ants go marchingthe append archery argument array associative arrow (on lines) ascii assignment statement assignment statement - semantics simultaneous syntax associative array atm simulation attendee list attributes private average numbers algorithm empty string sentinel problem description program counted loop
19,895
empty string sentinel end-of-file loop from file with readlines interactive loop negative sentinel average two numbers average py average py average py average py average py average py avg py babysitting base conversion batch processing example program binary binary search bit black box blackjack bmi (body mass index) boolean algebra (logic) expression operator values break statement implementing post-test loop style considerations bridge (card game) brooksfred bug butterfly effect button class definition description methods button py byte code -curve caesar cipher calculator problem description program cannonball algorithm graphical display problem description program projectile class card deck of cball py cball py cball py cbutton cd celsius censor change counter program change py change py chaos discussion - program chaos py chr christmas cipher ciphertext circle constructor methods circle area formula intersection with line class class standing class statement classes button calculator dice dieview graphicsinterface msdie player pokerapp projectile projectile as module file rballgame
19,896
simstats student textinterface client clone close graphwin code duplication in future value graph maintenance issues reducing with functions coffee collatz sequence color changing graphics object changing graphwin fill outline specifying color_rgb combinations command shell comments compiler diagram vs interpreter compound condition computer definition of functional view program computer science definition of methods of investigation concatenation list string condition compound design issues for termination syntax conditional loop constructor __init__ parameters in control codes control structure decision definition of loop nested loops nesting control structures boolean operators for statement if if-elif-else if-else while convert py convert py convert_gui pyw coordinates as instance variables changing with setcoords in graphwin of point setcoords example transforming counted loop definition of in python cpu (central processing unit) craps createlabeledwindow cryptography cube data data type automatic conversion definition of explicit conversion mixed-type expressions string conversion string conversions data types file float int long int string date date conversion program
19,897
dateconvert py dateconvert py day number debugging decision implementation via boolean operator multi-way nested simple (one-way) two-way decision tree deck decoding algorithm program definite loop definition of use as counted loop degree-days delete demorgan' laws design object-orientedsee object-oriented design top-down steps in design pattern importance of design patterns counted loop end-of-file loop interactive loop ipo loop accumulator model-view nested loops sentinel loop loop and half design techniques divide and conquer spiral development when to use dice dice poker classes dice graphicsinterface pokerapp textinterface problem description dice roller problem description program dictionary creation empty methods dieview class definition description dijkstraedsger disk distance function division docstring dot notation draw drawbar duplicate removal duplicationsee code duplication dvd easter elif empty list empty string encapsulation encoding algorithm program encryption entry - environmentprogramming epact equality eratosthenes error checking errors keyerror math domain name euclid' algorithm eval event event loop event-driven exam grader
19,898
exception handling exponential notation expression as input boolean definition of spaces in face fact py factorial definition of program recursive definition factorial py fahrenheit fetch-execute cycle fib recursive function fibonacci numbers file closing opening processing program to print read operations representation write operations flash memory float literal representation floppy flowchart flowcharts for loop if semantics loop and half sentinel max-of-three decision tree max-of-three sequential solution nested decisions post-test loop temperature conversion with warnings two-way decision while loop for statement (for loop) as counted loop flowchart semantics syntax using simultaneous assignment formal parameter format specifier from import function actual parameters arguments as black box as subprogram call createlabeledwindow defining for modularity invokingsee functioncall missing return multiple parameters none as default return parameters recursive return value returning multiple values signature (interface) to reduce duplication function definition functions anagrams built-in chr eval float int len max open ord range read readline readlines round str type write distance drawbar fib
19,899
gameover getinputs getnumbers happy loopfib looppower main why use makestudent math librarysee math libraryfunctions mean median merge mergesort movetower random librarysee random libraryfunctions recpower recursive binary search recursive factorial reverse selsort simngames simonegame singfred singlucy square stddev string librarysee string library future value algorithm problem description program program specification future value graph final algorithm problem program rough algorithm futval py futval_graph py futval_graph py futval_graph py futval_graph py gameover gcd (greatest common divisor) getanchor getcenter getinputs getmouse example use getnumbers getp getp getpoints getradius gettext getx gety gozinta gpa gpa program gpa sort program gpa py gpasort gpasort py graphics library methods setcoords graphics group graphics library - drawing example generic methods summary graphical objects - methods for text clone for circle for entry for image for line for oval for point for polygon for rectangle getmouse move objects circle entry - graphwin image line oval