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...
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...
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...
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 ...
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 winpo...
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 b...
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 ac...
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 [( , ,' ')( , ,')( , ,' ')( , ,' ')( , ,' ')( , ,'+')( , ,'-')( , ,' ')( , ,' ')( , ,' ')( , ,'*'...
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 "catch...
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 ...
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 typea...
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'),('newuse...
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 ...
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 alphabe...
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 the...
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...
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 ...
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 dcaf...
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...
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 writ...
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 u...
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 statse...
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 a...
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 softw...
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 graph...
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...
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...
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 ...
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 metho...
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...
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 t...
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...
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 pr...
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 a...
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 divisio...
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 develope...
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 object...
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 imple...
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 indica...
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 pro...
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 ...
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 i...
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 mod...
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 ...
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 a...
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 bu...
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 pi...
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 di...
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 o...
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 ...
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 ...
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 allow...
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 s...
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 s...
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 supercl...
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 spl...
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 functio...
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...
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 compa...
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 ...
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 analy...
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...
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 def...
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 probl...
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 ...
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 functio...
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...
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 va...
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 ...
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 t...
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 ve...
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...
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 eff...
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 follo...
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 m...
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 siz...
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 ...
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 legen...
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 woul...
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 ne...
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...
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 everyth...
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...
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...
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 co...
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 loo...
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 t...
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 o...
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...
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(...
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...
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 int...
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) ...
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 comp...
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-d...
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 representati...
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 s...