id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
21,800 | - consider the following "justificationthat the fibonacci functionf( (see proposition is ( )base case ( < ) ( and ( induction step ( )assume claim true for consider (nf( ( by inductionf( is ( and ( is ( thenf(nis (( ( ))by the identity presented in exercise - thereforef(nis (nwhat is wrong with this "justification" - consider the fibonacci functionf( (see proposition show by induction that (nis (( / ) - let (xbe polynomial of degree nthat isp(xni= ai xi (adescribe simple ( )-time algorithm for computing ( (bdescribe an ( log )-time algorithm for computing ( )based upon more efficient calculation of xi (cnow consider rewriting of (xas (xa ( ( ( (an- xan )))which is known as horner' method using the big-oh notationcharacterize the number of arithmetic operations this method executes - show that the summation ni= log is ( log nc- show that the summation ni= log is ( log nc- an evil king has bottles of wineand spy has just poisoned one of them unfortunatelythey do not know which one it is the poison is very deadlyjust one drop diluted even billion to one will still kill even soit takes full month for the poison to take effect design scheme for determining exactly which one of the wine bottles was poisoned in just one month' time while expending (log ntaste testers - sequence contains integers taken from the interval [ ]with repetitions allowed describe an efficient algorithm for determining an integer value that occurs the most often in what is the running time of your algorithmprojects - perform an experimental analysis of the three algorithms prefix average prefix average and prefix average from section visualize their running times as function of the input size with log-log chart - perform an experimental analysis that compares the relative running times of the functions shown in code fragment |
21,801 | - perform experimental analysis to test the hypothesis that python' sorted method runs in ( log ntime on average - for each of the three algorithmsunique unique and unique which solve the element uniqueness problemperform an experimental analysis to determine the largest value of such that the given algorithm runs in one minute or less notes the big-oh notation has prompted several comments about its proper use [ knuth [ defines it using the notation (no( ( ))but says this "equalityis only "one way we have chosen to take more standard view of equality and view the big-oh notation as setfollowing brassard [ the reader interested in studying average-case analysis is referred to the book by vitter and flajolet [ for some additional mathematical toolsplease refer to appendix |
21,802 | recursion contents illustrative examples the factorial function drawing an english ruler binary search file systems analyzing recursive algorithms recursion run amok maximum recursive depth in python further examples of recursion linear recursion binary recursion multiple recursion designing recursive algorithms eliminating tail recursion exercises |
21,803 | one way to describe repetition within computer program is the use of loopssuch as python' while-loop and for-loop constructs described in section an entirely different way to achieve repetition is through process known as recursion recursion is technique by which function makes one or more calls to itself during executionor by which data structure relies upon smaller instances of the very same type of structure in its representation there are many examples of recursion in art and nature for examplefractal patterns are naturally recursive physical example of recursion used in art is in the russian matryoshka dolls each doll is either made of solid woodor is hollow and contains another matryoshka doll inside it in computingrecursion provides an elegant and powerful alternative for performing repetitive tasks in facta few programming languages ( schemesmalltalkdo not explicitly support looping constructs and instead rely directly on recursion to express repetition most modern programming languages support functional recursion using the identical mechanism that is used to support traditional forms of function calls when one invocation of the function make recursive callthat invocation is suspended until the recursive call completes recursion is an important technique in the study of data structures and algorithms we will use it prominently in several later of this book (most notably and in this we begin with the following four illustrative examples of the use of recursionproviding python implementation for each the factorial function (commonly denoted as !is classic mathematical function that has natural recursive definition an english ruler has recursive pattern that is simple example of fractal structure binary search is among the most important computer algorithms it allows us to efficiently locate desired value in data set with upwards of billions of entries the file system for computer has recursive structure in which directories can be nested arbitrarily deeply within other directories recursive algorithms are widely used to explore and manage these file systems we then describe how to perform formal analysis of the running time of recursive algorithm and we discuss some potential pitfalls when defining recursions in the balance of the we provide many more examples of recursive algorithmsorganized to highlight some common forms of design |
21,804 | illustrative examples the factorial function to demonstrate the mechanics of recursionwe begin with simple mathematical example of computing the value of the factorial function the factorial of positive integer ndenoted !is defined as the product of the integers from to if then nis defined as by convention more formallyfor any integer > ( ( if if > for example the factorial function is important because it is known to equal the number of ways in which distinct items can be arranged into sequencethat isthe number of permutations of items for examplethe three characters aband can be arranged in waysabcacbbacbcacaband cba there is natural recursive definition for the factorial function to see thisobserve that ( more generallyfor positive integer nwe can define nto be ( )this recursive definition can be formalized as ( )if if > this definition is typical of many recursive definitions firstit contains one or more base caseswhich are defined nonrecursively in terms of fixed quantities in this casen is the base case it also contains one or more recursive caseswhich are defined by appealing to the definition of the function being defined recursive implementation of the factorial function recursion is not just mathematical notationwe can use recursion to design python implementation of factorial functionas shown in code fragment def factorial( ) if = return else return factorial( - code fragment recursive implementation of the factorial function |
21,805 | this function does not use any explicit loops repetition is provided by the repeated recursive invocations of the function there is no circularity in this definitionbecause each time the function is invokedits argument is smaller by oneand when base case is reachedno further recursive calls are made we illustrate the execution of recursive function using recursion trace each entry of the trace corresponds to recursive call each new recursive function call is indicated by downward arrow to new invocation when the function returnsan arrow showing this return is drawn and the return value may be indicated alongside this arrow an example of such trace for the factorial function is shown in figure return factorial( return = factorial( return = factorial( return = factorial( return factorial( figure recursion trace for the call factorial( recursion trace closely mirrors the programming language' execution of the recursion in pythoneach time function (recursive or otherwiseis calleda structure known as an activation record or frame is created to store information about the progress of that invocation of the function this activation record includes namespace for storing the function call' parameters and local variables (see section for discussion of namespaces)and information about which command in the body of the function is currently executing when the execution of function leads to nested function callthe execution of the former call is suspended and its activation record stores the place in the source code at which the flow of control should continue upon return of the nested call this process is used both in the standard case of one function calling different functionor in the recursive case in which function invokes itself the key point is that there is different activation record for each active call |
21,806 | drawing an english ruler in the case of computing factorialthere is no compelling reason for preferring recursion over direct iteration with loop as more complex example of the use of recursionconsider how to draw the markings of typical english ruler for each inchwe place tick with numeric label we denote the length of the tick designating whole inch as the major tick length between the marks for whole inchesthe ruler contains series of minor ticksplaced at intervals of / inch / inchand so on as the size of the interval decreases by halfthe tick length decreases by one figure demonstrates several such rulers with varying major tick lengths (although not drawn to scale--- -- --- --- --- ( ( (cfigure three sample outputs of an english ruler drawing(aa -inch ruler with major tick length (ba -inch ruler with major tick length (ca -inch ruler with major tick length recursive approach to ruler drawing the english ruler pattern is simple example of fractalthat isa shape that has self-recursive structure at various levels of magnification consider the rule with major tick length shown in figure (bignoring the lines containing and let us consider how to draw the sequence of ticks lying between these lines the central tick (at / inchhas length observe that the two patterns of ticks above and below this central tick are identicaland each has central tick of length |
21,807 | in generalan interval with central tick length > is composed ofan interval with central tick length single tick of length an interval with central tick length although it is possible to draw such ruler using an iterative process (see exercise - )the task is considerably easier to accomplish with recursion our implementation consists of three functionsas shown in code fragment the main functiondraw rulermanages the construction of the entire ruler its arguments specify the total number of inches in the ruler and the major tick length the utility functiondraw linedraws single tick with specified number of dashes (and an optional string labelthat is printed after the tickthe interesting work is done by the recursive draw interval function this function draws the sequence of minor ticks within some intervalbased upon the length of the interval' central tick we rely on the intuition shown at the top of this pageand with base case when that draws nothing for > the first and last steps are performed by recursively calling draw interval( the middle step is performed by calling the function draw line( def draw line(tick lengthtick label) """draw one line with given tick length (followed by optional label""tick length line if tick labeltick label line + print(line def draw interval(center length) """draw tick interval based upon central tick length ""stop when length drops to if center length recursively draw top ticks draw interval(center length draw center tick draw line(center lengthrecursively draw bottom ticks draw interval(center length def draw ruler(num inchesmajor length) """draw english ruler with given number of inchesmajor tick length ""draw inch line draw line(major length for in range( num inches)draw interior ticks for inch draw interval(major length draw inch line and label draw line(major lengthstr( )code fragment recursive implementation of function that draws ruler |
21,808 | illustrating ruler drawing using recursion trace the execution of the recursive draw interval function can be visualized using recursion trace the trace for draw interval is more complicated than in the factorial examplehoweverbecause each instance makes two recursive calls to illustrate thiswe will show the recursion trace in form that is reminiscent of an outline for document see figure output draw interval( draw interval( draw interval( draw interval( draw line( draw interval( draw line( draw interval( draw interval( draw line( draw interval( draw line( draw interval( (previous pattern repeatsfigure partial recursion trace for the call draw interval( the second pattern of calls for draw interval( is not shownbut it is identical to the first |
21,809 | binary search in this sectionwe describe classic recursive algorithmbinary searchthat is used to efficiently locate target value within sorted sequence of elements this is among the most important of computer algorithmsand it is the reason that we so often store data in sorted order (as in figure figure values stored in sorted order within an indexable sequencesuch as python list the numbers at top are the indices when the sequence is unsortedthe standard approach to search for target value is to use loop to examine every elementuntil either finding the target or exhausting the data set this is known as the sequential search algorithm this algorithm runs in (ntime ( linear timesince every element is inspected in the worst case when the sequence is sorted and indexablethere is much more efficient algorithm (for intuitionthink about how you would accomplish this task by hand!for any index jwe know that all the values stored at indices are less than or equal to the value at index jand all the values stored at indices are greater than or equal to that at index this observation allows us to quickly "home inon search target using variant of the children' game "high-low we call an element of the sequence candidate ifat the current stage of the searchwe cannot rule out that this item matches the target the algorithm maintains two parameterslow and highsuch that all the candidate entries have index at least low and at most high initiallylow and high we then compare the target value to the median candidatethat isthe item data[midwith index mid (low high)/ we consider three casesif the target equals data[mid]then we have found the item we are looking forand the search terminates successfully if target data[mid]then we recur on the first half of the sequencethat ison the interval of indices from low to mid if target data[mid]then we recur on the second half of the sequencethat ison the interval of indices from mid to high an unsuccessful search occurs if low highas the interval [lowhighis empty |
21,810 | this algorithm is known as binary search we give python implementation in code fragment and an illustration of the execution of the algorithm in figure whereas sequential search runs in (ntimethe more efficient binary search runs in (log ntime this is significant improvementgiven that if is one billionlog is only (we defer our formal analysis of binary search' running time to proposition in section def binary search(datatargetlowhigh) """return true if target is found in indicated portion of python list the search only considers the portion from data[lowto data[highinclusive "" if low high return false interval is emptyno match else mid (low high/ if target =data[mid]found match return true elif target data[mid] recur on the portion left of the middle return binary search(datatargetlowmid else recur on the portion right of the middle return binary search(datatargetmid highcode fragment an implementation of the binary search algorithm low mid high low mid high low mid high low=mid=high figure example of binary search for target value |
21,811 | file systems modern operating systems define file-system directories (which are also sometimes called "folders"in recursive way namelya file system consists of top-level directoryand the contents of this directory consists of files and other directorieswhich in turn can contain files and other directoriesand so on the operating system allows directories to be nested arbitrarily deep (as long as there is enough space in memory)although there must necessarily be some base directories that contain only filesnot further subdirectories representation of portion of such file system is given in figure /user/rt/coursescs cs grades homeworkshw hw hw programspr pr projectspr papersbuylow sellhigh grades demosmarket figure portion of file system demonstrating nested organization given the recursive nature of the file-system representationit should not come as surprise that many common behaviors of an operating systemsuch as copying directory or deleting directoryare implemented with recursive algorithms in this sectionwe consider one such algorithmcomputing the total disk usage for all files and directories nested within particular directory for illustrationfigure portrays the disk space being used by all entries in our sample file system we differentiate between the immediate disk space used by each entry and the cumulative disk space used by that entry and all nested features for examplethe cs directory uses only of immediate spacebut total of of cumulative space |
21,812 | /user/rt/courses cs cs grades homeworks programs projects hw hw hw pr pr pr grades papers demos buylow sellhigh market figure the same portion of file system given in figure but with additional annotations to describe the amount of disk space that is used within the icon for each file or directory is the amount of space directly used by that artifact above the icon for each directory is an indication of the cumulative disk space used by that directory and all its (recursivecontents the cumulative disk space for an entry can be computed with simple recursive algorithm it is equal to the immediate disk space used by the entry plus the sum of the cumulative disk space usage of any entries that are stored directly within the entry for examplethe cumulative disk space for cs is because it uses itself cumulatively in grades cumulatively in homeworksand cumulatively in programs pseudo-code for this algorithm is given in code fragment algorithm diskusage(path)inputa string designating path to file-system entry outputthe cumulative disk space used by that entry and any nested entries total size(path{immediate disk space used by the entryif path represents directory then for each child entry stored within directory path do total total diskusage(child{recursive callreturn total code fragment an algorithm for computing the cumulative disk space usage nested at file-system entry function size returns the immediate disk space of an entry |
21,813 | python' os module to provide python implementation of recursive algorithm for computing disk usagewe rely on python' os modulewhich provides robust tools for interacting with the operating system during the execution of program this is an extensive librarybut we will only need the following four functionsos path getsize(pathreturn the immediate disk usage (measured in bytesfor the file or directory that is identified by the string path ( /user/rt/coursesos path isdir(pathreturn true if entry designated by string path is directoryfalse otherwise os listdir(pathreturn list of strings that are the names of all entries within directory designated by string path in our sample file systemif the parameter is /user/rt/coursesthis returns the list cs cs os path join(pathfilenamecompose the path string and filename string using an appropriate operating system separator between the two ( the character for unix/linux systemand the character for windowsreturn the string that represents the full path to the file python implementation with use of the os modulewe now convert the algorithm from code fragment into the python implementation of code fragment import os def disk usage(path) """return the number of bytes used by file/folder and any descendents "" total os path getsize(pathaccount for direct usage if os path isdir(path)if this is directory for filename in os listdir(path)then for each child childpath os path join(pathfilenamecompose full path to child add child' usage to total total +disk usage(childpath descriptive output (optional print { :< format(total)path return total return the grand total code fragment recursive function for reporting disk usage of file system |
21,814 | recursion trace to produce different form of recursion tracewe have included an extraneous print statement within our python implementation (line of code fragment the precise format of that output intentionally mirrors output that is produced by classic unix/linux utility named du (for "disk usage"it reports the amount of disk space used by directory and all contents nested withinand can produce verbose reportas given in figure our implementation of the disk usage function produces an identical resultwhen executed on the sample file system portrayed in figure during the execution of the algorithmexactly one recursive call is made for each entry in the portion of the file system that is considered because the print statement is made just before returning from recursive callthe output shown in figure reflects the order in which the recursive calls are completed in particularwe begin and end recursive call for each entry that is nested below another entrycomputing the nested cumulative disk space before we can compute and report the cumulative disk space for the containing entry for examplewe do not know the cumulative total for entry /user/rt/courses/cs until after the recursive calls regarding contained entries gradeshomeworksand programs complete /user/rt/courses/cs /grades /user/rt/courses/cs /homeworks/hw /user/rt/courses/cs /homeworks/hw /user/rt/courses/cs /homeworks/hw /user/rt/courses/cs /homeworks /user/rt/courses/cs /programs/pr /user/rt/courses/cs /programs/pr /user/rt/courses/cs /programs/pr /user/rt/courses/cs /programs /user/rt/courses/cs /user/rt/courses/cs /projects/papers/buylow /user/rt/courses/cs /projects/papers/sellhigh /user/rt/courses/cs /projects/papers /user/rt/courses/cs /projects/demos/market /user/rt/courses/cs /projects/demos /user/rt/courses/cs /projects /user/rt/courses/cs /grades /user/rt/courses/cs /user/rt/coursesfigure report of the disk usage for the file system shown in figure as generated by the unix/linux utility du (with command-line options -ak)or equivalently by our disk usage function from code fragment |
21,815 | analyzing recursive algorithms in we introduced mathematical techniques for analyzing the efficiency of an algorithmbased upon an estimate of the number of primitive operations that are executed by the algorithm we use notations such as big-oh to summarize the relationship between the number of operations and the input size for problem in this sectionwe demonstrate how to perform this type of running-time analysis to recursive algorithms with recursive algorithmwe will account for each operation that is performed based upon the particular activation of the function that manages the flow of control at the time it is executed stated another wayfor each invocation of the functionwe only account for the number of operations that are performed within the body of that activation we can then account for the overall number of operations that are executed as part of the recursive algorithm by taking the sumover all activationsof the number of operations that take place during each individual activation (as an asidethis is also the way we analyze nonrecursive function that calls other functions from within its body to demonstrate this style of analysiswe revisit the four recursive algorithms presented in sections through factorial computationdrawing an english rulerbinary searchand computation of the cumulative size of file system in generalwe may rely on the intuition afforded by recursion trace in recognizing how many recursive activations occurand how the parameterization of each activation can be used to estimate the number of primitive operations that occur within the body of that activation howevereach of these recursive algorithms has unique structure and form computing factorials it is relatively easy to analyze the efficiency of our function for computing factorialsas described in section sample recursion trace for our factorial function was given in figure to compute factorial( )we see that there are total of activationsas the parameter decreases from in the first callto in the second calland so onuntil reaching the base case with parameter it is also cleargiven an examination of the function body in code fragment that each individual activation of factorial executes constant number of operations thereforewe conclude that the overall number of operations for computing factorial(nis ( )as there are activationseach of which accounts for ( operations |
21,816 | drawing an english ruler in analyzing the english ruler application from section we consider the fundamental question of how many total lines of output are generated by an initial call to draw interval( )where denotes the center length this is reasonable benchmark for the overall efficiency of the algorithm as each line of output is based upon call to the draw line utilityand each recursive call to draw interval with nonzero parameter makes exactly one direct call to draw line some intuition may be gained by examining the source code and the recursion trace we know that call to draw interval(cfor spawns two calls to draw interval( - and single call to draw line we will rely on this intuition to prove the following claim proposition for > call to draw interval(cresults in precisely lines of output justificationwe provide formal proof of this claim by induction (see section in factinduction is natural mathematical technique for proving the correctness and efficiency of recursive process in the case of the rulerwe note that an application of draw interval( generates no outputand that this serves as base case for our claim more generallythe number of lines printed by draw interval(cis one more than twice the number generated by call to draw interval( - )as one center line is printed between two such recursive calls by inductionwe have that the number of lines is thus ( - this proof is indicative of more mathematically rigorous toolknown as recurrence equation that can be used to analyze the running time of recursive algorithm that technique is discussed in section in the context of recursive sorting algorithms performing binary search considering the running time of the binary search algorithmas presented in section we observe that constant number of primitive operations are executed at each recursive call of method of binary search hencethe running time is proportional to the number of recursive calls performed we will show that at most log recursive calls are made during binary search of sequence having elementsleading to the following claim proposition the binary search algorithm runs in (log ntime for sorted sequence with elements |
21,817 | justificationto prove this claima crucial fact is that with each recursive call the number of candidate entries still to be searched is given by the value high low moreoverthe number of remaining candidates is reduced by at least one half with each recursive call specificallyfrom the definition of midthe number of remaining candidates is either high low low high low <(mid low or high low low high <high (mid high initiallythe number of candidates is nafter the first call in binary searchit is at most / after the second callit is at most / and so on in generalafter the jth call in binary searchthe number of candidate entries remaining is at most / in the worst case (an unsuccessful search)the recursive calls stop when there are no more candidate entries hencethe maximum number of recursive calls performedis the smallest integer such that in other words (recalling that we omit logarithm' base when it is ) log thuswe have log which implies that binary search runs in (log ntime computing disk space usage our final recursive algorithm from section was that for computing the overall disk space usage in specified portion of file system to characterize the "problem sizefor our analysiswe let denote the number of file-system entries in the portion of the file system that is considered (for examplethe file system portrayed in figure has entries to characterize the cumulative time spent for an initial call to the disk usage functionwe must analyze the total number of recursive invocations that are madeas well as the number of operations that are executed within those invocations we begin by showing that there are precisely recursive invocations of the functionin particularone for each entry in the relevant portion of the file system intuitivelythis is because call to disk usage for particular entry of the file system is only made from within the for loop of code fragment when processing the entry for the unique directory that contains eand that entry will only be explored once |
21,818 | recursion to formalize this argumentwe can define the nesting level of each entry such that the entry on which we begin has nesting level entries stored directly within it have nesting level entries stored within those entries have nesting level and so on we can prove by induction that there is exactly one recursive invocation of disk usage upon each entry at nesting level as base casewhen the only recursive invocation made is the initial one as the inductive steponce we know there is exactly one recursive invocation for each entry at nesting level kwe can claim that there is exactly one invocation for each entry at nesting level kmade within the for loop for the entry at level that contains having established that there is one recursive call for each entry of the file systemwe return to the question of the overall computation time for the algorithm it would be great if we could argue that we spend ( time in any single invocation of the functionbut that is not the case while there are constant number of steps reflect in the call to os path getsize to compute the disk usage directly at that entrywhen the entry is directorythe body of the disk usage function includes for loop that iterates over all entries that are contained within that directory in the worst caseit is possible that one entry includes others based on this reasoningwe could conclude that there are (nrecursive callseach of which runs in (ntimeleading to an overall running time that is ( while this upper bound is technically trueit is not tight upper bound remarkablywe can prove the stronger bound that the recursive algorithm for disk usage completes in (ntimethe weaker bound was pessimistic because it assumed worst-case number of entries for each directory while it is possible that some directories contain number of entries proportional to nthey cannot all contain that many to prove the stronger claimwe choose to consider the overall number of iterations of the for loop across all recursive calls we claim there are precisely such iteration of that loop overall we base this claim on the fact that each iteration of that loop makes recursive call to disk usageand yet we have already concluded that there are total of calls to disk usage (including the original callwe therefore conclude that there are (nrecursive callseach of which uses ( time outside the loopand that the overall number of operations due to the loop is (nsumming all of these boundsthe overall number of operations is (nthe argument we have made is more advanced than with the earlier examples of recursion the idea that we can sometimes get tighter bound on series of operations by considering the cumulative effectrather than assuming that each achieves worst case is technique called amortizationwe will see further example of such analysis in section furthermorea file system is an implicit example of data structure known as treeand our disk usage algorithm is really manifestation of more general algorithm known as tree traversal trees will be the focus of and our argument about the (nrunning time of the disk usage algorithm will be generalized for tree traversals in section |
21,819 | recursion run amok although recursion is very powerful toolit can easily be misused in various ways in this sectionwe examine several problems in which poorly implemented recursion causes drastic inefficiencyand we discuss some strategies for recognizing and avoid such pitfalls we begin by revisiting the element uniqueness problemdefined on page of section we can use the following recursive formulation to determine if all elements of sequence are unique as base casewhen the elements are trivially unique for > the elements are unique if and only if the first elements are uniquethe last items are uniqueand the first and last elements are different (as that is the only pair that was not already checked as subcasea recursive implementation based on this idea is given in code fragment named unique (to differentiate it from unique and unique from def unique (sstartstop) """return true if there are no duplicate elements in slice [start:stop"" if stop start < return true at most one item elif not unique(sstartstop- )return false first part has duplicate elif not unique(sstart+ stop)return false second part has duplicate elsereturn [start! [stop- do first and last differcode fragment recursive unique for testing element uniqueness unfortunatelythis is terribly inefficient use of recursion the nonrecursive part of each call uses ( timeso the overall running time will be proportional to the total number of recursive invocations to analyze the problemwe let denote the number of entries under considerationthat islet nstop start if then the running time of unique is ( )since there are no recursive calls for this case in the general casethe important observation is that single call to unique for problem of size may result in two recursive calls on problems of size those two calls with size could in turn result in four calls (two eachwith range of size and thus eight calls with size and so on thusin the worst casethe total number of function calls is given by the geometric summation - which is equal to by proposition thusthe running time of function unique is ( this is an incredibly inefficient function for solving the element uniqueness problem its inefficiency comes not from the fact that it uses recursion--it comes from the fact that it uses recursion poorlywhich is something we address in exercise - |
21,820 | an inefficient recursion for computing fibonacci numbers in section we introduced process for generating the fibonacci numberswhich can be defined recursively as followsf fn fn- fn- for ironicallya direct implementation based on this definition results in the function bad fibonacci shown in code fragment which computes the sequence of fibonacci numbers by making two recursive calls in each non-base case def bad fibonacci( ) """return the nth fibonacci number "" if < return else return bad fibonacci( - bad fibonacci( - code fragment computing the nth fibonacci number using binary recursion unfortunatelysuch direct implementation of the fibonacci formula results in terribly inefficient function computing the nth fibonacci number in this way requires an exponential number of calls to the function specificallylet cn denote the number of calls performed in the execution of bad fibonacci(nthenwe have the following values for the cn 'sc if we follow the pattern forwardwe see that the number of calls more than doubles for each two consecutive indices that isc is more than twice is more than twice is more than twice and so on thuscn / which means that bad fibonacci(nmakes number of calls that is exponential in |
21,821 | an efficient recursion for computing fibonacci numbers we were tempted into using the bad recursion formulation because of the way the nth fibonacci numberfn depends on the two previous valuesfn- and fn- but notice that after computing fn- the call to compute fn- requires its own recursive call to compute fn- as it does not have knowledge of the value of fn- that was computed at the earlier level of recursion that is duplicative work worse yetboth of those calls will need to (re)compute the value of fn- as will the computation of fn- this snowballing effect is what leads to the exponential running time of bad recursion we can compute fn much more efficiently using recursion in which each invocation makes only one recursive call to do sowe need to redefine the expectations of the function rather than having the function return single valuewhich is the nth fibonacci numberwe define recursive function that returns pair of consecutive fibonacci numbers (fn fn- )using the convention - although it seems to be greater burden to report two consecutive fibonacci numbers instead of onepassing this extra information from one level of the recursion to the next makes it much easier to continue the process (it allows us to avoid having to recompute the second value that was already known within the recursion an implementation based on this strategy is given in code fragment def good fibonacci( ) """return pair of fibonacci numbersf(nand ( - "" if < return ( , else (abgood fibonacci( - return ( +bacode fragment computing the nth fibonacci number using linear recursion in terms of efficiencythe difference between the bad recursion and the good recursion for this problem is like night and day the bad fibonacci function uses exponential time we claim that the execution of function good fibonacci(ntakes (ntime each recursive call to good fibonacci decreases the argument by thereforea recursion trace includes series of function calls because the nonrecursive work for each call uses constant timethe overall computation executes in (ntime |
21,822 | maximum recursive depth in python another danger in the misuse of recursion is known as infinite recursion if each recursive call makes another recursive callwithout ever reaching base casethen we have an infinite series of such calls this is fatal error an infinite recursion can quickly swamp computing resourcesnot only due to rapid use of the cpubut because each successive call creates an activation record requiring additional memory blatant example of an ill-formed recursion is the followingdef fib( )return fib(nfib(nequals fib(nhoweverthere are far more subtle errors that can lead to an infinite recursion revisiting our implementation of binary search in code fragment in the final case (line we make recursive call on the right portion of the sequencein particular going from index mid+ to high had that line instead been written as return binary search(datatargetmidhighnote the use of mid this could result in an infinite recursion in particularwhen searching range of two elementsit becomes possible to make recursive call on the identical range programmer should ensure that each recursive call is in some way progressing toward base case (for exampleby having parameter value that decreases with each callhoweverto combat against infinite recursionsthe designers of python made an intentional decision to limit the overall number of function activations that can be simultaneously active the precise value of this limit depends upon the python distributionbut typical default value is if this limit is reachedthe python interpreter raises runtimeerror with messagemaximum recursion depth exceeded for many legitimate applications of recursiona limit of nested function calls suffices for exampleour binary search function (section has (log nrecursive depthand so for the default recursive limit to be reachedthere would need to be elements (farfar more than the estimated number of atoms in the universehoweverin the next section we discuss several algorithms that have recursive depth proportional to python' artificial limit on the recursive depth could disrupt such otherwise legitimate computations fortunatelythe python interpreter can be dynamically reconfigured to change the default recursive limit this is done through use of module named syswhich supports getrecursionlimit function and setrecursionlimit sample usage of those functions is demonstrated as followsimport sys old sys getrecursionlimitsys setrecursionlimit( perhaps is typical change to allow million nested calls |
21,823 | further examples of recursion in the remainder of this we provide additional examples of the use of recursion we organize our presentation by considering the maximum number of recursive calls that may be started from within the body of single activation if recursive call starts at most one otherwe call this linear recursion if recursive call may start two otherswe call this binary recursion if recursive call may start three or more othersthis is multiple recursion linear recursion if recursive function is designed so that each invocation of the body makes at most one new recursive callthis is know as linear recursion of the recursions we have seen so farthe implementation of the factorial function (section and the good fibonacci function (section are clear examples of linear recursion more interestinglythe binary search algorithm (section is also an example of linear recursiondespite the "binaryterminology in the name the code for binary search (code fragment includes case analysis with two branches that lead to recursive callsbut only one of those calls can be reached during particular execution of the body consequence of the definition of linear recursion is that any recursion trace will appear as single sequence of callsas we originally portrayed for the factorial function in figure of section note that the linear recursion terminology reflects the structure of the recursion tracenot the asymptotic analysis of the running timefor examplewe have seen that binary search runs in (log ntime summing the elements of sequence recursively linear recursion can be useful tool for processing data sequencesuch as python list supposefor examplethat we want to compute the sum of sequencesof integers we can solve this summation problem using linear recursion by observing that the sum of all integers in is trivially if and otherwise that it is the sum of the first integers in plus the last element in (see figure figure computing the sum of sequence recursivelyby adding the last number to the sum of the first |
21,824 | recursive algorithm for computing the sum of sequence of numbers based on this intuition is implemented in code fragment def linear sum(sn) """return the sum of the first numbers of sequence "" if = return else return linear sum(sn- [ - code fragment summing the elements of sequence using linear recursion recursion trace of the linear sum function for small example is given in figure for an input of size nthe linear sum algorithm makes function calls henceit will take (ntimebecause it spends constant amount of time performing the nonrecursive part of each call moreoverwe can also see that the memory space used by the algorithm (in addition to the sequence sis also ( )as we use constant amount of memory space for each of the activation records in the trace at the time we make the final recursive call (with return [ linear sum( return [ linear sum( return [ linear sum( return [ linear sum( return [ linear sum( return linear sum( figure recursion trace for an execution of linear sum( with input parameter [ |
21,825 | reversing sequence with recursion nextlet us consider the problem of reversing the elements of sequencesso that the first element becomes the lastthe second element becomes second to the lastand so on we can solve this problem using linear recursionby observing that the reversal of sequence can be achieved by swapping the first and last elements and then recursively reversing the remaining elements we present an implementation of this algorithm in code fragment using the convention that the first time we call this algorithm we do so as reverse( len( ) def reverse(sstartstop) """reverse elements in implicit slice [start:stop"" if start stop if at least elements [start] [stop- [stop- ] [startswap first and last reverse(sstart+ stop- recur on rest code fragment reversing the elements of sequence using linear recursion note that there are two implicit base case scenarioswhen start =stopthe implicit range is emptyand when start =stop- the implicit range has only one element in either of these casesthere is no need for actionas sequence with zero elements or one element is trivially equal to its reversal when otherwise invoking recursionwe are guaranteed to make progress towards base caseas the differencestop-startdecreases by two with each call (see figure if is evenwe will eventually reach the start =stop caseand if is oddwe will eventually reach the start =stop case the above argument implies that the recursive algorithm of code fragment is guaranteed to terminate after total of recursive calls since each call involves constant amount of workthe entire process runs in (ntime figure trace of the recursion for reversing sequence the shaded portion has yet to be reversed |
21,826 | recursive algorithms for computing powers as another interesting example of the use of linear recursionwe consider the problem of raising number to an arbitrary nonnegative integern that iswe wish to compute the power functiondefined as power(xnxn (we use the name "powerfor this discussionto differentiate from the built-in function pow that provides such functionality we will consider two different recursive formulations for the problem that lead to algorithms with very different performance trivial recursive definition follows from the fact that xn xn- for if power(xnx power(xn otherwise this definition leads to recursive algorithm shown in code fragment def power(xn) """compute the value for integer "" if = return else return power(xn- code fragment computing the power function using trivial recursion recursive call to this version of power(xnruns in (ntime its recursion trace has structure very similar to that of the factorial function from figure with the parameter decreasing by one with each calland constant work performed at each of levels howeverthere is much faster way to compute the power function using an alternative definition that employs squaring technique let denote the floor of the division (expressed as / in pythonwe consider the expression xk when is evenn and therefore xk xn when is oddn - xn- and therefore xn xk just as and this analysis leads to the following recursive definitionif if is odd power(xnx power xn power xn if is even if we were to implement this recursion making two recursive calls to compute power( power( ) trace of the recursion would demonstrate (ncalls we can perform significantly fewer operations by computing power(xn as partial resultand then multiplying it by itself an implementation based on this recursive definition is given in code fragment |
21,827 | def power(xn) """compute the value for integer "" if = return else partial power(xn / rely on truncated division result partial partial if = if oddinclude extra factor of result return result code fragment computing the power function using repeated squaring to illustrate the execution of our improved algorithmfigure provides recursion trace of the computation power( return power( return power( return = power( return = power( return power( figure recursion trace for an execution of power( to analyze the running time of the revised algorithmwe observe that the exponent in each recursive call of function power( ,nis at most half of the preceding exponent as we saw with the analysis of binary searchthe number of times that we can divide in half before getting to one or less is (log nthereforeour new formulation of the power function results in (log nrecursive calls each individual activation of the function uses ( operations (excluding the recursive calls)and so the total number of operations for computing power( ,nis (log nthis is significant improvement over the original ( )-time algorithm the improved version also provides significant saving in reducing the memory usage the first version has recursive depth of ( )and therefore (nactivation records are simultaneous stored in memory because the recursive depth of the improved version is (log )its memory usages is (log nas well |
21,828 | binary recursion when function makes two recursive callswe say that it uses binary recursion we have already seen several examples of binary recursionmost notably when drawing the english ruler (section )or in the bad fibonacci function of section as another application of binary recursionlet us revisit the problem of summing the elements of sequencesof numbers computing the sum of one or zero elements is trivial with two or more elementswe can recursively compute the sum of the first halfand the sum of the second halfand add these sums together our implementation of such an algorithmin code fragment is initially invoked as binary sum( len( ) def binary sum(sstartstop) """return the sum of the numbers in implicit slice [start:stop"" if start >stopzero elements in slice return elif start =stop- one element in slice return [start elsetwo or more elements in slice mid (start stop/ return binary sum(sstartmidbinary sum(smidstopcode fragment summing the elements of sequence using binary recursion to analyze algorithm binary sumwe considerfor simplicitythe case where is power of two figure shows the recursion trace of an execution of binary sum( we label each box with the values of parameters start:stop for that call the size of the range is divided in half at each recursive calland so the depth of the recursion is log thereforebinary sum uses (log namount of additional spacewhich is big improvement over the (nspace used by the linear sum function of code fragment howeverthe running time of binary sum is ( )as there are function callseach requiring constant time : : : : : : : : : : : : : : : figure recursion trace for the execution of binary sum( |
21,829 | multiple recursion generalizing from binary recursionwe define multiple recursion as process in which function may make more than two recursive calls our recursion for analyzing the disk space usage of file system (see section is an example of multiple recursionbecause the number of recursive calls made during one invocation was equal to the number of entries within given directory of the file system another common application of multiple recursion is when we want to enumerate various configurations in order to solve combinatorial puzzle for examplethe following are all instances of what are known as summation puzzlespot pan bib dog cat pig boy girl baby to solve such puzzlewe need to assign unique digit (that is to each letter in the equationin order to make the equation true typicallywe solve such puzzle by using our human observations of the particular puzzle we are trying to solve to eliminate configurations (that ispossible partial assignments of digits to lettersuntil we can work though the feasible configurations lefttesting for the correctness of each one if the number of possible configurations is not too largehoweverwe can use computer to simply enumerate all the possibilities and test each onewithout employing any human observations in additionsuch an algorithm can use multiple recursion to work through the configurations in systematic way we show pseudocode for such an algorithm in code fragment to keep the description general enough to be used with other puzzlesthe algorithm enumerates and tests all klength sequences without repetitions of the elements of given universe we build the sequences of elements by the following steps recursively generating the sequences of elements appending to each such sequence an element not already contained in it throughout the execution of the algorithmwe use set to keep track of the elements not contained in the current sequenceso that an element has not been used yet if and only if is in another way to look at the algorithm of code fragment is that it enumerates every possible size- ordered subset of and tests each subset for being possible solution to our puzzle for summation puzzlesu { and each position in the sequence corresponds to given letter for examplethe first position could stand for bthe second for othe third for yand so on |
21,830 | algorithm puzzlesolve( , , )inputan integer ksequence sand set outputan enumeration of all -length extensions to using elements in without repetitions for each in do add to the end of remove from { is now being usedif = then test whether is configuration that solves the puzzle if solves the puzzle then return "solution founds else puzzlesolve( - , , { recursive callremove from the end of add back to { is now considered as unusedcode fragment solving combinatorial puzzle by enumerating and testing all possible configurations in figure we show recursion trace of call to puzzlesolve( , )where is empty and {abcduring the executionall the permutations of the three characters are generated and tested note that the initial call makes three recursive callseach of which in turn makes two more if we had executed puzzlesolve( , on set consisting of four elementsthe initial call would have made four recursive callseach of which would have trace looking like the one in figure initial call puzzlesolve( ){ , , }puzzlesolve( { , }puzzlesolve( ab{ }abc puzzlesolve( { , }puzzlesolve( ba{ }bac puzzlesolve( ac{ }acb puzzlesolve( { , }puzzlesolve( ca{ }cab puzzlesolve( bc{ }bca puzzlesolve( cb{ }cba figure recursion trace for an execution of puzzlesolve( , )where is empty and {abcthis execution generates and tests all permutations of aband we show the permutations generated directly below their respective boxes |
21,831 | designing recursive algorithms in generalan algorithm that uses recursion typically has the following formtest for base cases we begin by testing for set of base cases (there should be at least onethese base cases should be defined so that every possible chain of recursive calls will eventually reach base caseand the handling of each base case should not use recursion recur if not base casewe perform one or more recursive calls this recursive step may involve test that decides which of several possible recursive calls to make we should define each possible recursive call so that it makes progress towards base case parameterizing recursion to design recursive algorithm for given problemit is useful to think of the different ways we might define subproblems that have the same general structure as the original problem if one has difficulty finding the repetitive structure needed to design recursive algorithmit is sometimes useful to work out the problem on few concrete examples to see how the subproblems should be defined successful recursive design sometimes requires that we redefine the original problem to facilitate similar-looking subproblems oftenthis involved reparameterizing the signature of the function for examplewhen performing binary search in sequencea natural function signature for caller would appear as binary search(datatargethoweverin section we defined our function with calling signature binary search(datatargetlowhigh)using the additional parameters to demarcate sublists as the recursion proceeds this change in parameterization is critical for binary search if we had insisted on the cleaner signaturebinary search(datatarget)the only way to invoke search on half the list would have been to make new list instance with only those elements to send as the first parameter howevermaking copy of half the list would already take (ntimenegating the whole benefit of the binary search algorithm if we wished to provide cleaner public interface to an algorithm like binary searchwithout bothering user with the extra parametersa standard technique is to make one function for public use with the cleaner interfacesuch as binary search(datatarget)and then having its body invoke nonpublic utility function having the desired recursive parameters you will see that we similarly reparameterized the recursion in several other examples of this ( reverselinear sumbinary sumwe saw different approach to redefining recursion in our good fibonacci implementationby intentionally strengthening the expectation of what is returned (in that casereturning pair of numbers rather than single number |
21,832 | eliminating tail recursion the main benefit of recursive approach to algorithm design is that it allows us to succinctly take advantage of repetitive structure present in many problems by making our algorithm description exploit the repetitive structure in recursive waywe can often avoid complex case analyses and nested loops this approach can lead to more readable algorithm descriptionswhile still being quite efficient howeverthe usefulness of recursion comes at modest cost in particularthe python interpreter must maintain activation records that keep track of the state of each nested call when computer memory is at premiumit is useful in some cases to be able to derive nonrecursive algorithms from recursive ones in generalwe can use the stack data structurewhich we will introduce in section to convert recursive algorithm into nonrecursive algorithm by managing the nesting of the recursive structure ourselvesrather than relying on the interpreter to do so although this only shifts the memory usage from the interpreter to our stackwe may be able to reduce the memory usage by storing only the minimal information necessary even bettersome forms of recursion can be eliminated without any use of axillary memory notable such form is known as tail recursion recursion is tail recursion if any recursive call that is made from one context is the very last operation in that contextwith the return value of the recursive call (if anyimmediately returned by the enclosing recursion by necessitya tail recursion must be linear recursion (since there is no way to make second recursive call if you must immediately return the result of the firstof the recursive functions demonstrated in this the binary search function of code fragment and the reverse function of code fragment are examples of tail recursion several others of our linear recursions are almost like tail recursionbut not technically so for exampleour factorial function of code fragment is not tail recursion it concludes with the commandreturn factorial( - this is not tail recursion because an additional multiplication is performed after the recursive call is completed for similar reasonsthe linear sum function of code fragment and the good fibonacci function of code fragment fail to be tail recursions any tail recursion can be reimplemented nonrecursively by enclosing the body in loop for repetitionand replacing recursive call with new parameters by reassignment of the existing parameters to those values as tangible exampleour binary search function can be reimplemented as shown in code fragment we initialize variables low and highjust prior to our while loopto represent the full extent of the sequence thenduring each pass of the loopwe either find |
21,833 | def binary search iterative(datatarget) """return true if target is found in the given python list "" low high len(data)- while low <high mid (low high/ if target =data[mid]found match return true elif target data[mid] high mid only consider values left of mid else low mid only consider values right of mid return false loop ended without success code fragment nonrecursive implementation of binary search the targetor we narrow the range of the candidate subsequence where we made the recursive call binary search(datatargetlowmid - in the original versionwe simply replace high mid in our new version and then continue to the next iteration of the loop our original base case condition of low high has simply been replaced by the opposite loop condition while low <high in our new implementationwe return false to designate failed search if the while loop ends (that iswithout having ever returned true from withinwe can similarly develop nonrecursive implementation (code fragment of the original recursive reverse method of code fragment def reverse iterative( ) """reverse elements in sequence "" startstop len( while start stop [start] [stop- [stop- ] [start startstop start stop swap first and last narrow the range code fragment reversing the elements of sequence using iteration in this new versionwe update the values start and stop during each pass of the loopexiting once we reach the case of having one or less elements in that range many other linear recursions can be expressed quite efficiently with iterationeven if they were not formally tail recursions for examplethere are trivial nonrecursive implementations for computing factorialssumming elements of sequenceor computing fibonacci numbers efficiently in factour implementation of fibonacci generatorfrom section produces each subsequent value in ( timeand thus takes (ntime to generate the nth entry in the series |
21,834 | exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - describe recursive algorithm for finding the maximum element in sequencesof elements what is your running time and space usager- draw the recursion trace for the computation of power( )using the traditional function implemented in code fragment - draw the recursion trace for the computation of power( )using the repeated squaring algorithmas implemented in code fragment - draw the recursion trace for the execution of function reverse( (code fragment on [ - draw the recursion trace for the execution of function puzzlesolve( , (code fragment )where is empty and {abcdr- describe recursive function for computing the nth harmonic numberhn ni= / - describe recursive function for converting string of digits into the integer it represents for example represents the integer - isabel has an interesting way of summing up the values in sequence of integerswhere is power of two she creates new sequence of half the size of and sets [ia[ ia[ ]for ( / if has size then she outputs [ otherwiseshe replaces with band repeats the process what is the running time of her algorithmcreativity - write short recursive python function that finds the minimum and maximum values in sequence without using any loops - describe recursive algorithm to compute the integer part of the base-two logarithm of using only addition and integer division - describe an efficient recursive function for solving the element uniqueness problemwhich runs in time that is at most ( in the worst case without using sorting - give recursive algorithm to compute the product of two positive integersm and nusing only addition and subtraction |
21,835 | - in section we prove by induction that the number of lines printed by call to draw interval(cis another interesting question is how many dashes are printed during that process prove by induction that the number of dashes printed by draw interval(cis + - in the towers of hanoi puzzlewe are given platform with three pegsaband csticking out of it on peg is stack of diskseach larger than the nextso that the smallest is on the top and the largest is on the bottom the puzzle is to move all the disks from peg to peg cmoving one disk at timeso that we never place larger disk on top of smaller one see figure for an example of the case describe recursive algorithm for solving the towers of hanoi puzzle for arbitrary (hintconsider first the subproblem of moving all but the nth disk from peg to another peg using the third as "temporary storage "figure an illustration of the towers of hanoi puzzle - write recursive function that will output all the subsets of set of elements (without repeating any subsetsc- write short recursive python function that takes character string and outputs its reverse for examplethe reverse of pots&pans would be snap&stop - write short recursive python function that determines if string is palindromethat isit is equal to its reverse for exampleracecar and gohangasalamiimalasagnahog are palindromes - use recursion to write python function for determining if string has more vowels than consonants - write short recursive python function that rearranges sequence of integer values so that all the even values appear before all the odd values - given an unsorted sequencesof integers and an integer kdescribe recursive algorithm for rearranging the elements in so that all elements less than or equal to come before any elements larger than what is the running time of your algorithm on sequence of values |
21,836 | - suppose you are given an -element sequencescontaining distinct integers that are listed in increasing order given number kdescribe recursive algorithm to find two integers in that sum to kif such pair exists what is the running time of your algorithmc- develop nonrecursive implementation of the version of power from code fragment that uses repeated squaring projects - implement recursive function with signature find(pathfilenamethat reports all entries of the file system rooted at the given path having the given file name - write program for solving summation puzzles by enumerating and testing all possible configurations using your programsolve the three puzzles given in section - provide nonrecursive implementation of the draw interval function for the english ruler project of section there should be precisely lines of output if represents the length of the center tick if incrementing counter from to the number of dashes for each tick line should be exactly one more than the number of consecutive ' at the end of the binary representation of the counter - write program that can solve instances of the tower of hanoi problem (from exercise - - python' os module provides function with signature walk(paththat is generator yielding the tuple (dirpathdirnamesfilenamesfor each subdirectory of the directory identified by string pathsuch that string dirpath is the full path to the subdirectorydirnames is list of the names of the subdirectories within dirpathand filenames is list of the names of non-directory entries of dirpath for examplewhen visiting the cs subdirectory of the file system shown in figure the walk would yield /user/rt/courses/cs homeworks programs ]grades ]give your own implementation of such walk function notes the use of recursion in programs belongs to the folkore of computer science (for examplesee the article of dijkstra [ ]it is also at the heart of functional programming languages (for examplesee the classic book by abelsonsussmanand sussman [ ]interestinglybinary search was first published in but was not published in fully correct form until for further discussions on lessons learnedplease see papers by bentley [ and lesuisse [ |
21,837 | array-based sequences contents python' sequence types low-level arrays referential arrays compact arrays in python dynamic arrays and amortization implementing dynamic array amortized analysis of dynamic arrays python' list class efficiency of python' sequence types python' list and tuple classes python' string class using array-based sequences storing high scores for game sorting sequence simple cryptography multidimensional data sets exercises |
21,838 | python' sequence types in this we explore python' various "sequenceclassesnamely the builtin listtupleand str classes there is significant commonality between these classesmost notablyeach supports indexing to access an individual element of sequenceusing syntax such as seq[ ]and each uses low-level concept known as an array to represent the sequence howeverthere are significant differences in the abstractions that these classes representand in the way that instances of these classes are represented internally by python because these classes are used so widely in python programsand because they will become building blocks upon which we will develop more complex data structuresit is imperative that we establish clear understanding of both the public behavior and inner workings of these classes public behaviors proper understanding of the outward semantics for class is necessity for good programmer while the basic usage of listsstringsand tuples may seem straightforwardthere are several important subtleties regarding the behaviors associated with these classes (such as what it means to make copy of sequenceor to take slice of sequencehaving misunderstanding of behavior can easily lead to inadvertent bugs in program thereforewe establish an accurate mental model for each of these classes these images will help when exploring more advanced usagesuch as representing multidimensional data set as list of lists implementation details focus on the internal implementations of these classes seems to go against our stated principles of object-oriented programming in section we emphasized the principle of encapsulationnoting that the user of class need not know about the internal details of the implementation while it is true that one only needs to understand the syntax and semantics of class' public interface in order to be able to write legal and correct code that uses instances of the classthe efficiency of program depends greatly on the efficiency of the components upon which it relies asymptotic and experimental analyses in describing the efficiency of various operations for python' sequence classeswe will rely on the formal asymptotic analysis notations established in we will also perform experimental analyses of the primary operations to provide empirical evidence that is consistent with the more theoretical asymptotic analyses |
21,839 | low-level arrays to accurately describe the way in which python represents the sequence typeswe must first discuss aspects of the low-level computer architecture the primary memory of computer is composed of bits of informationand those bits are typically grouped into larger units that depend upon the precise system architecture such typical unit is bytewhich is equivalent to bits computer system will have huge number of bytes of memoryand to keep track of what information is stored in what bytethe computer uses an abstraction known as memory address in effecteach byte of memory is associated with unique number that serves as its address (more formallythe binary representation of the number serves as the addressin this waythe computer system can refer to the data in "byte # versus the data in "byte # ,for example memory addresses are typically coordinated with the physical layout of the memory systemand so we often portray the numbers in sequential fashion figure provides such diagramwith the designated memory address for each byte figure representation of portion of computer' memorywith individual bytes labeled with consecutive memory addresses despite the sequential nature of the numbering systemcomputer hardware is designedin theoryso that any byte of the main memory can be efficiently accessed based upon its memory address in this sensewe say that computer' main memory performs as random access memory (ramthat isit is just as easy to retrieve byte # as it is to retrieve byte # (in practicethere are complicating factors including the use of caches and external memorywe address some of those issues in using the notation for asymptotic analysiswe say that any individual byte of memory can be stored or retrieved in ( time in generala programming language keeps track of the association between an identifier and the memory address in which the associated value is stored for exampleidentifier might be associated with one value stored in memorywhile is associated with another value stored in memory common programming task is to keep track of sequence of related objects for examplewe may want video game to keep track of the top ten scores for that game rather than use ten different variables for this taskwe would prefer to use single name for the group and use index numbers to refer to the high scores in that group |
21,840 | group of related variables can be stored one after another in contiguous portion of the computer' memory we will denote such representation as an array as tangible examplea text string is stored as an ordered sequence of individual characters in pythoneach character is represented using the unicode character setand on most computing systemspython internally represents each unicode character with bits ( bytesthereforea six-character stringsuch as sample would be stored in consecutive bytes of memoryas diagrammed in figure figure python string embedded as an array of characters in the computer' memory we assume that each unicode character of the string requires two bytes of memory the numbers below the entries are indices into the string we describe this as an array of six characterseven though it requires bytes of memory we will refer to each location within an array as celland will use an integer index to describe its location within the arraywith cells numbered starting with and so on for examplein figure the cell of the array with index has contents and is stored in bytes and of memory each cell of an array must use the same number of bytes this requirement is what allows an arbitrary cell of the array to be accessed in constant time based on its index in particularif one knows the memory address at which an array starts ( in figure )the number of bytes per element ( for unicode character)and desired index within the arraythe appropriate memory address can be computed using the calculationstart cellsize index by this formulathe cell at index begins precisely at the start of the arraythe cell at index begins precisely cellsize bytes beyond the start of the arrayand so on as an examplecell of figure begins at memory location of coursethe arithmetic for calculating memory addresses within an array can be handled automatically thereforea programmer can envision more typical high-level abstraction of an array of characters as diagrammed in figure figure higher-level abstraction for the string portrayed in figure |
21,841 | referential arrays as another motivating exampleassume that we want medical information system to keep track of the patients currently assigned to beds in certain hospital if we assume that the hospital has bedsand conveniently that those beds are numbered from to we might consider using an array-based structure to maintain the names of the patients currently assigned to those beds for examplein python we might use list of namessuch asrene joseph janet jonas helen virginia to represent such list with an arraypython must adhere to the requirement that each cell of the array use the same number of bytes yet the elements are stringsand strings naturally have different lengths python could attempt to reserve enough space for each cell to hold the maximum length string (not just of currently stored stringsbut of any string we might ever want to store)but that would be wasteful insteadpython represents list or tuple instance using an internal storage mechanism of an array of object references at the lowest levelwhat is stored is consecutive sequence of memory addresses at which the elements of the sequence reside high-level diagram of such list is shown in figure janet jonas joseph helen rene virginia figure an array storing references to strings although the relative size of the individual elements may varythe number of bits used to store the memory address of each element is fixed ( -bits per addressin this waypython can support constant-time access to list or tuple element based on its index in figure we characterize list of strings that are the names of the patients in hospital it is more likely that medical information system would manage more comprehensive information on each patientperhaps represented as an instance of patient class from the perspective of the list implementationthe same principle appliesthe list will simply keep sequence of references to those objects note as well that reference to the none object can be used as an element of the list to represent an empty bed in the hospital |
21,842 | the fact that lists and tuples are referential structures is significant to the semantics of these classes single list instance may include multiple references to the same object as elements of the listand it is possible for single object to be an element of two or more listsas those lists simply store references back to that object as an examplewhen you compute slice of listthe result is new list instancebut that new list has references to the same elements that are in the original listas portrayed in figure temp primes figure the result of the command temp primes[ : when the elements of the list are immutable objectsas with the integer instances in figure the fact that the two lists share elements is not that significantas neither of the lists can cause change to the shared object iffor examplethe command temp[ were executed from this configurationthat does not change the existing integer objectit changes the reference in cell of the temp list to reference different object the resulting configuration is shown in figure temp primes figure the result of the command temp[ upon the configuration portrayed in figure the same semantics is demonstrated when making new list as copy of an existing onewith syntax such as backup list(primesthis produces new list that is shallow copy (see section )in that it references the same elements as in the first list with immutable elementsthis point is moot if the contents of the list were of mutable typea deep copymeaning new list with new elementscan be produced by using the deepcopy function from the copy module |
21,843 | as more striking exampleit is common practice in python to initialize an array of integers using syntax such as counters [ this syntax produces list of length eightwith all eight elements being the value zero technicallyall eight cells of the list reference the same objectas portrayed in figure counters figure the result of the command data [ at first glancethe extreme level of aliasing in this configuration may seem alarming howeverwe rely on the fact that the referenced integer is immutable even command such as counters[ + does not technically change the value of the existing integer instance this computes new integerwith value and sets cell to reference the newly computed value the resulting configuration is shown in figure counters figure the result of command data[ + upon the list from figure as final manifestation of the referential nature of listswe note that the extend command is used to add all elements from one list to the end of another list the extended list does not receive copies of those elementsit receives references to those elements figure portrays the effect of call to extend extras primes figure the effect of command primes extend(extras)shown in light gray |
21,844 | compact arrays in python in the introduction to this sectionwe emphasized that strings are represented using an array of characters (not an array of referenceswe will refer to this more direct representation as compact array because the array is storing the bits that represent the primary data (charactersin the case of stringss compact arrays have several advantages over referential structures in terms of computing performance most significantlythe overall memory usage will be much lower for compact structure because there is no overhead devoted to the explicit storage of the sequence of memory references (in addition to the primary datathat isa referential structure will typically use -bits for the memory address stored in the arrayon top of whatever number of bits are used to represent the object that is considered the element alsoeach unicode character stored in compact array within string typically requires bytes if each character were stored independently as one-character stringthere would be significantly more bytes used as another case studysuppose we wish to store sequence of one million -bit integers in theorywe might hope to use only million bits howeverwe estimate that python list will use four to five times as much memory each element of the list will result in -bit memory address being stored in the primary arrayand an int instance being stored elsewhere in memory python allows you to query the actual number of bytes being used for the primary storage of any object this is done using the getsizeof function of the sys module on our systemthe size of typical int object requires bytes of memory (well beyond the bytes needed for representing the actual -bit numberin allthe list will be using bytes per entryrather than the bytes that compact list of integers would require another important advantage to compact structure for high-performance computing is that the primary data are stored consecutively in memory note well that this is not the case for referential structure that iseven though list maintains careful ordering of the sequence of memory addresseswhere those elements reside in memory is not determined by the list because of the workings of the cache and memory hierarchies of computersit is often advantageous to have data stored in memory near other data that might be used in the same computations despite the apparent inefficiencies of referential structureswe will generally be content with the convenience of python' lists and tuples in this book the only place in which we consider alternatives will be in which focuses on the impact of memory usage on data structures and algorithms python provides several means for creating compact arrays of various types |
21,845 | primary support for compact arrays is in module named array that module defines classalso named arrayproviding compact storage for arrays of primitive data types portrayal of such an array of integers is shown in figure figure integers stored compactly as elements of python array the public interface for the array class conforms mostly to that of python list howeverthe constructor for the array class requires type code as first parameterwhich is character that designates the type of data that will be stored in the array as tangible examplethe type codei designates an array of (signedintegerstypically represented using at least -bits each we can declare the array shown in figure asprimes arrayi [ ]the type code allows the interpreter to determine precisely how many bits are needed per element of the array the type codes supported by the array moduleas shown in table are formally based upon the native data types used by the programming language (the language in which the the most widely used distribution of python is implementedthe precise number of bits for the data types is system-dependentbut typical ranges are shown in the table code data type signed char unsigned char unicode char signed short int unsigned short int signed int unsigned int signed long int unsigned long int float float typical number of bytes or or or table type codes supported by the array module the array module does not provide support for making compact arrays of userdefined data types compact arrays of such structures can be created with the lowerlevel support of module named ctypes (see section for more discussion of the ctypes module |
21,846 | dynamic arrays and amortization when creating low-level array in computer systemthe precise size of that array must be explicitly declared in order for the system to properly allocate consecutive piece of memory for its storage for examplefigure displays an array of bytes that might be stored in memory locations through figure an array of bytes allocated in memory locations through because the system might dedicate neighboring memory locations to store other datathe capacity of an array cannot trivially be increased by expanding into subsequent cells in the context of representing python tuple or str instancethis constraint is no problem instances of those classes are immutableso the correct size for an underlying array can be fixed when the object is instantiated python' list class presents more interesting abstraction although list has particular length when constructedthe class allows us to add elements to the listwith no apparent limit on the overall capacity of the list to provide this abstractionpython relies on an algorithmic sleight of hand known as dynamic array the first key to providing the semantics of dynamic array is that list instance maintains an underlying array that often has greater capacity than the current length of the list for examplewhile user may have created list with five elementsthe system may have reserved an underlying array capable of storing eight object references (rather than only fivethis extra capacity makes it easy to append new element to the list by using the next available cell of the array if user continues to append elements to listany reserved capacity will eventually be exhausted in that casethe class requests newlarger array from the systemand initializes the new array so that its prefix matches that of the existing smaller array at that point in timethe old array is no longer neededso it is reclaimed by the system intuitivelythis strategy is much like that of the hermit crabwhich moves into larger shell when it outgrows its previous one we give empirical evidence that python' list class is based upon such strategy the source code for our experiment is displayed in code fragment and sample output of that program is given in code fragment we rely on function named getsizeof that is available from the sys module this function reports the number of bytes that are being used to store an object in python for listit reports the number of bytes devoted to the array and other instance variables of the listbut not any space devoted to elements referenced by the list |
21,847 | import sys provides getsizeof function data for in range( )notemust fix choice of len(datanumber of elements sys getsizeof(dataactual size in bytes printlength{ : }size in bytes{ : dformat(ab) data append(noneincrease length by one code fragment an experiment to explore the relationship between list' length and its underlying size in python lengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlengthlength size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes size in bytes code fragment sample output from the experiment of code fragment |
21,848 | in evaluating the results of the experimentwe draw attention to the first line of output from code fragment we see that an empty list instance already requires certain number of bytes of memory ( on our systemin facteach object in python maintains some statefor examplea reference to denote the class to which it belongs although we cannot directly access private instance variables for listwe can speculate that in some form it maintains state information akin ton capacity the number of actual elements currently stored in the list the maximum number of elements that could be stored in the currently allocated array the reference to the currently allocated array (initially noneas soon as the first element is inserted into the listwe detect change in the underlying size of the structure in particularwe see the number of bytes jump from to an increase of exactly bytes our experiment was run on -bit machine architecturemeaning that each memory address is -bit number ( byteswe speculate that the increase of bytes reflects the allocation of an underlying array capable of storing four object references this hypothesis is consistent with the fact that we do not see any underlying change in the memory usage after inserting the secondthirdor fourth element into the list after the fifth element has been added to the listwe see the memory usage jump from bytes to bytes if we assume the original base usage of bytes for the listthe total of suggests an additional bytes that provide capacity for up to eight object references againthis is consistent with the experimentas the memory usage does not increase again until the ninth insertion at that pointthe bytes can be viewed as the original plus an additional -byte array to store object references the th insertion pushes the overall memory usage to hence enough to store up to element references because list is referential structurethe result of getsizeof for list instance only includes the size for representing its primary structureit does not account for memory used by the objects that are elements of the list in our experimentwe repeatedly append none to the listbecause we do not care about the contentsbut we could append any type of object without affecting the number of bytes reported by getsizeof(dataif we were to continue such an experiment for further iterationswe might try to discern the pattern for how large of an array python creates each time the capacity of the previous array is exhausted (see exercises - and - before exploring the precise sequence of capacities used by pythonwe continue in this section by describing general approach for implementing dynamic arrays and for performing an asymptotic analysis of their performance |
21,849 | implementing dynamic array although the python list class provides highly optimized implementation of dynamic arraysupon which we rely for the remainder of this bookit is instructive to see how such class might be implemented the key is to provide means to grow the array that stores the elements of list of coursewe cannot actually grow that arrayas its capacity is fixed if an element is appended to list at time when the underlying array is fullwe perform the following steps allocate new array with larger capacity set [ia[ ]for where denotes current number of items set bthat iswe henceforth use as the array supporting the list insert the new element in the new array an illustration of this process is shown in figure (aa ( (cfigure an illustration of the three steps for "growinga dynamic array(acreate new array (bstore elements of in (creassign reference to the new array not shown is the future garbage collection of the old arrayor the insertion of the new element the remaining issue to consider is how large of new array to create commonly used rule is for the new array to have twice the capacity of the existing array that has been filled in section we will provide mathematical analysis to justify such choice in code fragment we offer concrete implementation of dynamic arrays in python our dynamicarray class is designed using ideas described in this section while consistent with the interface of python list classwe provide only limited functionality in the form of an append methodand accessors len and getitem support for creating low-level arrays is provided by module named ctypes because we will not typically use such low-level structure in the remainder of this bookwe omit detailed explanation of the ctypes module insteadwe wrap the necessary command for declaring the raw array within private utility method make array the hallmark expansion procedure is performed in our nonpublic resize method |
21,850 | import ctypes provides low-level arrays class dynamicarray """ dynamic array class akin to simplified python list "" def init (self) """create an empty array ""count actual elements self default array capacity self capacity low-level array self self make array(self capacity def len (self) """return number of elements stored in the array "" return self def getitem (selfk) """return element at index "" if not < self raise indexerrorinvalid index retrieve from array return self [ def append(selfobj) """add object to end of the array ""not enough room if self =self capacityso double capacity self resize( self capacity self [self nobj self + nonpublic utitity def resize(selfc) """resize internal array to capacity ""new (biggerarray self make array(cfor each existing value for in range(self ) [kself [kuse the bigger array self self capacity nonpublic utitity def make array(selfc) """return new array with capacity ""see ctypes documentation return ( ctypes py object)code fragment an implementation of dynamicarray classusing raw array from the ctypes module as storage |
21,851 | amortized analysis of dynamic arrays primitive operations for an append in this sectionwe perform detailed analysis of the running time of operations on dynamic arrays we use the big-omega notation introduced in section to give an asymptotic lower bound on the running time of an algorithm or step within it the strategy of replacing an array with newlarger array might at first seem slowbecause single append operation may require (ntime to performwhere is the current number of elements in the array howevernotice that by doubling the capacity during an array replacementour new array allows us to add new elements before the array must be replaced again in this waythere are many simple append operations for each expensive one (see figure this fact allows us to show that performing series of operations on an initially empty dynamic array is efficient in terms of its total running time using an algorithmic design pattern called amortizationwe can show that performing sequence of such append operations on dynamic array is actually quite efficient to perform an amortized analysiswe use an accounting technique where we view the computer as coin-operated appliance that requires the payment of one cyber-dollar for constant amount of computing time when an operation is executedwe should have enough cyber-dollars available in our current "bank accountto pay for that operation' running time thusthe total amount of cyberdollars spent for any computation will be proportional to the total time spent on that computation the beauty of using this analysis method is that we can overcharge some operations in order to save up cyber-dollars to pay for others current number of elements figure running times of series of append operations on dynamic array |
21,852 | proposition let be sequence implemented by means of dynamic array with initial capacity oneusing the strategy of doubling the array size when full the total time to perform series of append operations in sstarting from being emptyis (njustificationlet us assume that one cyber-dollar is enough to pay for the execution of each append operation in sexcluding the time spent for growing the array alsolet us assume that growing the array from size to size requires cyberdollars for the time spent initializing the new array we shall charge each append operation three cyber-dollars thuswe overcharge each append operation that does not cause an overflow by two cyber-dollars think of the two cyber-dollars profited in an insertion that does not grow the array as being "storedwith the cell in which the element was inserted an overflow occurs when the array has elementsfor some integer > and the size of the array used by the array representing is thusdoubling the size of the array will require cyber-dollars fortunatelythese cyber-dollars can be found stored in cells - through (see figure note that the previous overflow occurred when the number of elements became larger than - for the first timeand thus the cyber-dollars stored in cells - through have not yet been spent thereforewe have valid amortization scheme in which each operation is charged three cyber-dollars and all the computing time is paid for that iswe can pay for the execution of append operations using cyber-dollars in other wordsthe amortized running time of each append operation is ( )hencethe total running time of append operations is ( ( ( figure illustration of series of append operations on dynamic array(aan -cell array is fullwith two cyber-dollars "storedat cells through (ban append operation causes an overflow and doubling of capacity copying the eight old elements to the new array is paid for by the cyber-dollars already stored in the table inserting the new element is paid for by one of the cyber-dollars charged to the current append operationand the two cyber-dollars profited are stored at cell |
21,853 | geometric increase in capacity although the proof of proposition relies on the array being doubled each time we expandthe ( amortized bound per operation can be proven for any geometrically increasing progression of array sizes (see section for discussion of geometric progressionswhen choosing the geometric basethere exists tradeoff between run-time efficiency and memory usage with base of ( doubling the array)if the last insertion causes resize eventthe array essentially ends up twice as large as it needs to be if we instead increase the array by only of its current size ( geometric base of )we do not risk wasting as much memory in the endbut there will be more intermediate resize events along the way still it is possible to prove an ( amortized boundusing constant factor greater than the cyber-dollars per operation used in the proof of proposition (see exercise - the key to the performance is that the amount of additional space is proportional to the current size of the array beware of arithmetic progression primitive operations for an append primitive operations for an append to avoid reserving too much space at onceit might be tempting to implement dynamic array with strategy in which constant number of additional cells are reserved each time an array is resized unfortunatelythe overall performance of such strategy is significantly worse at an extremean increase of only one cell causes each append operation to resize the arrayleading to familiar summation and ( overall cost using increases of or at time is slightly betteras portrayed in figure but the overall cost remains quadratic current number of elements current number of elements ( (bfigure running times of series of append operations on dynamic array using arithmetic progression of sizes (aassumes increase of in size of the arraywhile (bassumes increase of |
21,854 | array-based sequences using fixed increment for each resizeand thus an arithmetic progression of intermediate array sizesresults in an overall time that is quadratic in the number of operationsas shown in the following proposition intuitivelyeven an increase in cells per resize will become insignificant for large data sets proposition performing series of append operations on an initially empty dynamic array using fixed increment with each resize takes ( time justificationlet represent the fixed increment in capacity that is used for each resize event during the series of append operationstime will have been spent initializing arrays of size cmc for / and thereforethe overall time would be proportional to mc by proposition this sum is ( > >ci = = thereforeperforming the append operations takes ( time lesson to be learned from propositions and is that subtle difference in an algorithm design can produce drastic differences in the asymptotic performanceand that careful analysis can provide important insights into the design of data structure memory usage and shrinking an array another consequence of the rule of geometric increase in capacity when appending to dynamic array is that the final array size is guaranteed to be proportional to the overall number of elements that isthe data structure uses (nmemory this is very desirable property for data structure if containersuch as python listprovides operations that cause the removal of one or more elementsgreater care must be taken to ensure that dynamic array guarantees (nmemory usage the risk is that repeated insertions may cause the underlying array to grow arbitrarily largeand that there will no longer be proportional relationship between the actual number of elements and the array capacity after many elements are removed robust implementation of such data structure will shrink the underlying arrayon occasionwhile maintaining the ( amortized bound on individual operations howevercare must be taken to ensure that the structure cannot rapidly oscillate between growing and shrinking the underlying arrayin which case the amortized bound would not be achieved in exercise - we explore strategy in which the array capacity is halved whenever the number of actual element falls below one fourth of that capacitythereby guaranteeing that the array capacity is at most four times the number of elementswe explore the amortized analysis of such strategy in exercises - and - |
21,855 | python' list class the experiments of code fragment and at the beginning of section provide empirical evidence that python' list class is using form of dynamic arrays for its storage yeta careful examination of the intermediate array capacities (see exercises - and - suggests that python is not using pure geometric progressionnor is it using an arithmetic progression with that saidit is clear that python' implementation of the append method exhibits amortized constant-time behavior we can demonstrate this fact experimentally single append operation typically executes so quickly that it would be difficult for us to accurately measure the time elapsed at that granularityalthough we should notice some of the more expensive operations in which resize is performed we can get more accurate measure of the amortized cost per operation by performing series of append operations on an initially empty list and determining the average cost of each function to perform that experiment is given in code fragment from time import time import time function from time module def compute average( ) """perform appends to an empty list and return average time elapsed "" data start timerecord the start time (in seconds for in range( ) data append(none end timerecord the end time (in seconds return (end startn compute average per operation code fragment measuring the amortized cost of append for python' list class technicallythe time elapsed between the start and end includes the time to manage the iteration of the for loopin addition to the append calls the empirical results of the experimentfor increasingly large values of nare shown in table we see higher average cost for the smaller data setsperhaps in part due to the overhead of the loop range there is also natural variance in measuring the amortized cost in this waybecause of the impact of the final resize event relative to taken as wholethere seems clear evidence that the amortized time for each append is independent of ms , , , , , , , , , table average running time of appendmeasured in microsecondsas observed over sequence of callsstarting with an empty list |
21,856 | efficiency of python' sequence types in the previous sectionwe began to explore the underpinnings of python' list classin terms of implementation strategies and efficiency we continue in this section by examining the performance of all of python' sequence types python' list and tuple classes the nonmutating behaviors of the list class are precisely those that are supported by the tuple class we note that tuples are typically more memory efficient than lists because they are immutablethereforethere is no need for an underlying dynamic array with surplus capacity we summarize the asymptotic efficiency of the nonmutating behaviors of the list and tuple classes in table an explanation of this analysis follows operation len(datadata[jdata count(valuedata index(valuevalue in data data =data (similarly !=>=data[ :kdata data data running time ( ( (no( ( ( ( ( (cntable asymptotic performance of the nonmutating behaviors of the list and tuple classes identifiers datadata and data designate instances of the list or tuple classand nn and their respective lengths for the containment check and index methodk represents the index of the leftmost occurrence (with if there is no occurrencefor comparisons between two sequenceswe let denote the leftmost index at which they disagree or else min( constant-time operations the length of an instance is returned in constant time because an instance explicitly maintains such state information the constant-time efficiency of syntax data[jis assured by the underlying access into an array |
21,857 | searching for occurrences of value each of the countindexand contains methods proceed through iteration of the sequence from left to right in factcode fragment of section demonstrates how those behaviors might be implemented notablythe loop for computing the count must proceed through the entire sequencewhile the loops for checking containment of an element or determining the index of an element immediately exit once they find the leftmost occurrence of the desired valueif one exists so while count always examines the elements of the sequenceindex and contains examine elements in the worst casebut may be faster empirical evidence can be found by setting data list(range( )and then comparing the relative efficiency of the test in datarelative to the test in dataor even the failed test- in data lexicographic comparisons comparisons between two sequences are defined lexicographically in the worst caseevaluating such condition requires an iteration taking time proportional to the length of the shorter of the two sequences (because when one sequence endsthe lexicographic result can be determinedhoweverin some cases the result of the test can be evaluated more efficiently for exampleif evaluating [ [ ]it is clear that the result is true without examining the remainders of those listsbecause the second element of the left operand is strictly less than the second element of the right operand creating new instances the final three behaviors in table are those that construct new instance based on one or more existing instances in all casesthe running time depends on the construction and initialization of the new resultand therefore the asymptotic behavior is proportional to the length of the result thereforewe find that slice data[ : can be constructed almost immediately because it has only eight elementswhile slice data[ : has one million elementsand thus is more time-consuming to create mutating behaviors the efficiency of the mutating behaviors of the list class are described in table the simplest of those behaviors has syntax data[jvaland is supported by the special setitem method this operation has worst-case ( running time because it simply replaces one element of list with new value no other elements are affected and the size of the underlying array does not change the more interesting behaviors to analyze are those that add or remove elements from the list |
21,858 | operation data[jval data append(valuedata insert(kvaluedata popdata pop(kdel data[kdata remove(valuedata extend(data data +data data reversedata sortrunning time ( ( ) ( ) ( ) ( ) ( ) ( ) (no( log namortized table asymptotic performance of the mutating behaviors of the list class identifiers datadata and data designate instances of the list classand nn and their respective lengths adding elements to list in section we fully explored the append method in the worst caseit requires (ntime because the underlying array is resizedbut it uses ( time in the amortized sense lists also support methodwith signature insert(kvalue)that inserts given value into the list at index < < while shifting all subsequent elements back one slot to make room for the purpose of illustrationcode fragment provides an implementation of that methodin the context of our dynamicarray class introduced in code fragment there are two complicating factors in analyzing the efficiency of such an operation firstwe note that the addition of one element may require resizing of the dynamic array that portion of the work requires (nworst-case time but only ( amortized timeas per append the other expense for insert is the shifting of elements to make room for the new item the time for def insert(selfkvalue)"""insert value at index kshifting subsequent values rightward ""(for simplicitywe assume < < in this verionnot enough room if self =self capacityso double capacity self resize( self capacityshift rightmost first for in range(self nk- )self [jself [ - store newest element self [kvalue self + code fragment implementation of insert for our dynamicarray class |
21,859 | - figure creating room to insert new element at index of dynamic array that process depends upon the index of the new elementand thus the number of other elements that must be shifted that loop copies the reference that had been at index to index nthen the reference that had been at index to continuing until copying the reference that had been at index to as illustrated in figure overall this leads to an amortized ( performance for inserting at index when exploring the efficiency of python' append method in section we performed an experiment that measured the average cost of repeated calls on varying sizes of lists (see code fragment and table we have repeated that experiment with the insert methodtrying three different access patternsin the first casewe repeatedly insert at the beginning of listfor in range( )data insert( nonein second casewe repeatedly insert near the middle of listfor in range( )data insert( / nonein third casewe repeatedly insert at the end of the listfor in range( )data insert(nnonethe results of our experiment are given in table reporting the average time per operation (not the total time for the entire loopas expectedwe see that inserting at the beginning of list is most expensiverequiring linear time per operation inserting at the middle requires about half the time as inserting at the beginningyet is still (ntime inserting at the end displays ( behaviorakin to append = / = , , , , , table average running time of insert(kval)measured in microsecondsas observed over sequence of callsstarting with an empty list we let denote the size of the current list (as opposed to the final list |
21,860 | removing elements from list python' list class offers several ways to remove an element from list call to popremoves the last element from list this is most efficientbecause all other elements remain in their original location this is effectively an ( operationbut the bound is amortized because python will occasionally shrink the underlying dynamic array to conserve memory the parameterized versionpop( )removes the element that is at index of listshifting all subsequent elements leftward to fill the gap that results from the removal the efficiency of this operation is ( )as the amount of shifting depends upon the choice of index kas illustrated in figure note well that this implies that pop( is the most expensive callusing (ntime (see experiments in exercise - - figure removing an element at index of dynamic array the list class offers another methodnamed removethat allows the caller to specify the value that should be removed (not the index at which it residesformallyit removes only the first occurrence of such value from listor raises valueerror if no such value is found an implementation of such behavior is given in code fragment again using our dynamicarray class for illustration interestinglythere is no "efficientcase for removeevery call requires (ntime one part of the process searches from the beginning until finding the value at index kwhile the rest iterates from to the end in order to shift elements leftward this linear behavior can be observed experimentally (see exercise - def remove(selfvalue)"""remove first occurrence of value (or raise valueerror""notewe do not consider shrinking the dynamic array in this version for in range(self )found matchif self [ =valueshift others to fill gap for in range(kself )self [jself [ + self [self none help garbage collection we have one less item self - return exit immediately only reached if no match raise valueerrorvalue not found code fragment implementation of remove for our dynamicarray class |
21,861 | extending list python provides method named extend that is used to add all elements of one list to the end of second list in effecta call to data extend(otherproduces the same outcome as the codefor element in otherdata append(elementin either casethe running time is proportional to the length of the other listand amortized because the underlying array for the first list may be resized to accommodate the additional elements in practicethe extend method is preferable to repeated calls to append because the constant factors hidden in the asymptotic analysis are significantly smaller the greater efficiency of extend is threefold firstthere is always some advantage to using an appropriate python methodbecause those methods are often implemented natively in compiled language (rather than as interpreted python codesecondthere is less overhead to single function call that accomplishes all the workversus many individual function calls finallyincreased efficiency of extend comes from the fact that the resulting size of the updated list can be calculated in advance if the second data set is quite largethere is some risk that the underlying dynamic array might be resized multiple times when using repeated calls to append with single call to extendat most one resize operation will be performed exercise - explores the relative efficiency of these two approaches experimentally constructing new lists there are several syntaxes for constructing new lists in almost all casesthe asymptotic efficiency of the behavior is linear in the length of the list that is created howeveras with the case in the preceding discussion of extendthere are significant differences in the practical efficiency section introduces the topic of list comprehensionusing an example such as squares for in range( + as shorthand for squares for in range( + )squares append( kexperiments should show that the list comprehension syntax is significantly faster than building the list by repeatedly appending (see exercise - similarlyit is common python idiom to initialize list of constant values using the multiplication operatoras in [ to produce list of length with all values equal to zero not only is this succinct for the programmerit is more efficient than building such list incrementally |
21,862 | python' string class strings are very important in python we introduced their use in with discussion of various operator syntaxes in section comprehensive summary of the named methods of the class is given in tables through of appendix we will not formally analyze the efficiency of each of those behaviors in this sectionbut we do wish to comment on some notable issues in generalwe let denote the length of string for operations that rely on second string as patternwe let denote the length of that pattern string the analysis for many behaviors is quite intuitive for examplemethods that produce new string ( capitalizecenterstriprequire time that is linear in the length of the string that is produced many of the behaviors that test boolean conditions of string ( islowertake (ntimeexamining all characters in the worst casebut short circuiting as soon as the answer becomes evident ( islower can immediately return false if the first character is uppercasedthe comparison operators ( ==<fall into this category as well pattern matching some of the most interesting behaviorsfrom an algorithmic point of vieware those that in some way depend upon finding string pattern within larger stringthis goal is at the heart of methods such as contains findindexcountreplaceand split string algorithms will be the topic of and this particular problem known as pattern matching will be the focus of section naive implementation runs in (mntime casebecause we consider the possible starting indices for the patternand we spend (mtime at each starting positionchecking if the pattern matches howeverin section we will develop an algorithm for finding pattern of length within longer string of length in (ntime composing strings finallywe wish to comment on several approaches for composing large strings as an academic exerciseassume that we have large string named documentand our goal is to produce new stringlettersthat contains only the alphabetic characters of the original string ( with spacesnumbersand punctuation removedit may be tempting to compose result through repeated concatenationas follows warningdo not do this letters for in documentif isalpha)letters + start with empty string concatenate alphabetic character |
21,863 | while the preceding code fragment accomplishes the goalit may be terribly inefficient because strings are immutablethe commandletters +cwould presumably compute the concatenationletters cas new string instance and then reassign the identifierlettersto that result constructing that new string would require time proportional to its length if the final result has charactersthe series of concatenations would take time proportional to the familiar sum nand therefore ( time inefficient code of this type is widespread in pythonperhaps because of the somewhat natural appearance of the codeand mistaken presumptions about how the +operator is evaluated with strings some later implementations of the python interpreter have developed an optimization to allow such code to complete in linear timebut this is not guaranteed for all python implementations the optimization is as follows the reason that commandletters +ccauses new string instance to be created is that the original string must be left unchanged if another variable in program refers to that string on the other handif python knew that there were no other references to the string in questionit could implement +more efficiently by directly mutating the string (as dynamic arrayas it happensthe python interpreter already maintains what are known as reference counts for each objectthis count is used in part to determine if an object can be garbage collected (see section but in this contextit provides means to detect when no other references exist to stringthereby allowing the optimization more standard python idiom to guarantee linear time composition of string is to use temporary list to store individual piecesand then to rely on the join method of the str class to compose the final result using this technique with our previous example would appear as followstemp for in documentif isalpha)temp append(cletters join(tempstart with empty list append alphabetic character compose overall result this approach is guaranteed to run in (ntime firstwe note that the series of up to append calls will require total of (ntimeas per the definition of the amortized cost of that operation the final call to join also guarantees that it takes time that is linear in the final length of the composed string as we discussed at the end of the previous sectionwe can further improve the practical execution time by using list comprehension syntax to build up the temporary listrather than by repeated calls to append that solution appears asletters join([ for in document if isalpha)]better yetwe can entirely avoid the temporary list with generator comprehensionletters join( for in document if isalpha) |
21,864 | using array-based sequences storing high scores for game the first application we study is storing sequence of high score entries for video game this is representative of many applications in which sequence of objects must be stored we could just as easily have chosen to store records for patients in hospital or the names of players on football team neverthelesslet us focus on storing high score entrieswhich is simple application that is already rich enough to present some important data-structuring concepts to beginwe consider what information to include in an object representing high score entry obviouslyone component to include is an integer representing the score itselfwhich we identify as score another useful thing to include is the name of the person earning this scorewhich we identify as name we could go on from hereadding fields representing the date the score was earned or game statistics that led to that score howeverwe omit such details to keep our example simple python classgameentryrepresenting game entryis given in code fragment class gameentry """represents one entry of list of high scores "" def init (selfnamescore) self name name self score score def get name(self) return self name def get score(self) return self score def str (self) return ({ }{ }format(self nameself scoree (bob code fragment python code for simple gameentry class we include methods for returning the name and score for game entry objectas well as method for returning string representation of this entry |
21,865 | class for high scores to maintain sequence of high scoreswe develop class named scoreboard scoreboard is limited to certain number of high scores that can be savedonce that limit is reacheda new score only qualifies for the scoreboard if it is strictly higher than the lowest "high scoreon the board the length of the desired scoreboard may depend on the gameperhaps or since that limit may vary depending on the gamewe allow it to be specified as parameter to our scoreboard constructor internallywe will use python list named board in order to manage the gameentry instances that represent the high scores since we expect the scoreboard to eventually reach full capacitywe initialize the list to be large enough to hold the maximum number of scoresbut we initially set all entries to none by allocating the list with maximum capacity initiallyit never needs to be resized as entries are addedwe will maintain them from highest to lowest scorestarting at index of the list we illustrate typical state of the data structure in figure rob paul mike anna rose jack figure an illustration of an ordered list of length tenstoring references to six gameentry objects in the cells from index to with the rest being none complete python implementation of the scoreboard class is given in code fragment the constructor is rather simple the command self board [nonecapacity creates list with the desired lengthyet all entries equal to none we maintain an additional instance variablenthat represents the number of actual entries currently in our table for convenienceour class supports the getitem method to retrieve an entry at given index with syntax board[ (or none if no such entry exists)and we support simple str method that returns string representation of the entire scoreboardwith one entry per line |
21,866 | array-based sequences class scoreboard """fixed-length sequence of high scores in nondecreasing order "" def init (selfcapacity= ) """initialize scoreboard with given maximum capacity all entries are initially none ""reserve space for future scores self board [nonecapacity number of actual entries self def getitem (selfk) """return entry at index "" return self board[ def str (self) """return string representation of the high score list "" return \ join(str(self board[ ]for in range(self ) def add(selfentry) """consider adding entry to high scores "" score entry get score does new entry qualify as high score answer is yes if board not full or score is higher than last entry good self self board[- get score if goodno score drops from list if self len(self board)so overall number increases self + shift lower scores rightward to make room for new entry self while and self board[ - get scorescoreshift entry from - to self board[jself board[ - - and decrement when doneadd new entry self board[jentry code fragment python code for scoreboard class that maintains an ordered series of scores as gameentry objects |
21,867 | adding an entry the most interesting method of the scoreboard class is addwhich is responsible for considering the addition of new entry to the scoreboard keep in mind that every entry will not necessarily qualify as high score if the board is not yet fullany new entry will be retained once the board is fulla new entry is only retained if it is strictly better than one of the other scoresin particularthe last entry of the scoreboardwhich is the lowest of the high scores when new score is consideredwe begin by determining whether it qualifies as high score if sowe increase the count of active scoresnunless the board is already at full capacity in that caseadding new high score causes some other entry to be dropped from the scoreboardso the overall number of entries remains the same to correctly place new entry within the listthe final task is to shift any inferior scores one spot lower (with the least score being dropped entirely when the scoreboard is fullthis process is quite similar to the implementation of the insert method of the list classas described on pages - in the context of our scoreboardthere is no need to shift any none references that remain near the end of the arrayso the process can proceed as diagrammed in figure jill rob anna mike paul rose jack figure adding new gameentry for jill to the scoreboard in order to make room for the new referencewe have to shift the references for game entries with smaller scores than the new one to the right by one cell then we can insert the new entry with index to implement the final stagewe begin by considering index self which is the index at which the last gameentry instance will resideafter completing the operation either is the correct index for the newest entryor one or more immediately before it will have lesser scores the while loop at line checks the compound conditionshifting references rightward and decrementing jas long as there is another entry at index with score less than the new score |
21,868 | sorting sequence in the previous subsectionwe considered an application for which we added an object to sequence at given position while shifting other elements so as to keep the previous order intact in this sectionwe use similar technique to solve the sorting problemthat isstarting with an unordered sequence of elements and rearranging them into nondecreasing order the insertion-sort algorithm we study several sorting algorithms in this bookmost of which are described in as warm-upin this section we describe nicesimple sorting algorithm known as insertion-sort the algorithm proceeds as follows for an arraybased sequence we start with the first element in the array one element by itself is already sorted then we consider the next element in the array if it is smaller than the firstwe swap them next we consider the third element in the array we swap it leftward until it is in its proper order with the first two elements we then consider the fourth elementand swap it leftward until it is in the proper order with the first three we continue in this manner with the fifth elementthe sixthand so onuntil the whole array is sorted we can express the insertion-sort algorithm in pseudo-codeas shown in code fragment algorithm insertionsort( )inputan array of comparable elements outputthe array with elements rearranged in nondecreasing order for from to do insert [kat its proper location within [ ] [ ] [kcode fragment high-level description of the insertion-sort algorithm this is simplehigh-level description of insertion-sort if we look back to code fragment of section we see that the task of inserting new entry into the list of high scores is almost identical to the task of inserting newly considered element in insertion-sort (except that game scores were ordered from high to lowwe provide python implementation of insertion-sort in code fragment using an outer loop to consider each element in turnand an inner loop that moves newly considered element to its proper location relative to the (sortedsubarray of elements that are to its left we illustrate an example run of the insertion-sort algorithm in figure the nested loops of insertion-sort lead to an ( running time in the worst case the most work is done if the array is initially in reverse order on the other handif the initial array is nearly sorted or perfectly sortedinsertion-sort runs in (ntime because there are few or no iterations of the inner loop |
21,869 | def insertion sort( ) """sort list of comparable elements into nondecreasing order "" for in range( len( ))from to - cur [kcurrent element to be inserted = find correct index for current while and [ - curelement [ - must be after current [ja[ - - [jcur cur is now in the right place code fragment python code for performing insertion-sort on list cur no move move move no move move no move move insert no move insert move no move move insert no move done figure execution of the insertion-sort algorithm on an array of eight characters each row corresponds to an iteration of the outer loopand each copy of the sequence in row corresponds to an iteration of the inner loop the current element that is being inserted is highlighted in the arrayand shown as the cur value |
21,870 | simple cryptography an interesting application of strings and lists is cryptographythe science of secret messages and their applications this field studies ways of performing encryptionwhich takes messagecalled the plaintextand converts it into scrambled messagecalled the ciphertext likewisecryptography also studies corresponding ways of performing decryptionwhich takes ciphertext and turns it back into its original plaintext arguably the earliest encryption scheme is the caesar cipherwhich is named after julius caesarwho used this scheme to protect important military messages (all of caesar' messages were written in latinof coursewhich already makes them unreadable for most of us!the caesar cipher is simple way to obscure message written in language that forms words with an alphabet the caesar cipher involves replacing each letter in message with the letter that is certain number of letters after it in the alphabet soin an english messagewe might replace each with deach with eeach with fand so onif shifting by three characters we continue this approach all the way up to wwhich is replaced with thenwe let the substitution pattern wrap aroundso that we replace with ay with band with converting between strings and character lists given that strings are immutablewe cannot directly edit an instance to encrypt it insteadour goal will be to generate new string convenient technique for performing string transformations is to create an equivalent list of charactersedit the listand then reassemble (newstring based on the list the first step can be performed by sending the string as parameter to the constructor of the list class for examplethe expression listbird produces the result converselywe can use list of characters to build string by invoking the join method on an empty stringwith the list of characters as the parameter for examplethe call join( ]returns the string bird using characters as array indices if we were to number our letters like array indicesso that is is is and so onthen we can write the caesar cipher with rotation of as simple formulareplace each letter with the letter ( rmod where mod is the modulo operatorwhich returns the remainder after performing an integer division this operator is denoted with in pythonand it is exactly the operator we need to easily perform the wrap around at the end of the alphabet for mod is mod is and mod is the decryption algorithm for the caesar cipher is just the opposite--we replace each letter with the one places before itwith wrap around (that isletter is replaced by letter ( rmod |
21,871 | we can represent replacement rule using another string to describe the translation as concrete examplesuppose we are using caesar cipher with threecharacter rotation we can precompute string that represents the replacements that should be used for each character from to for examplea should be replaced by db replaced by eand so on the replacement characters in order are defghijklmnopqrstuvwxyzabc we can subsequently use this translation string as guide to encrypt message the remaining challenge is how to quickly locate the replacement for each character of the original message fortunatelywe can rely on the fact that characters are represented in unicode by integer code pointsand the code points for the uppercase letters of the latin alphabet are consecutive (for simplicitywe restrict our encryption to uppercase letterspython supports functions that convert between integer code points and one-character strings specificallythe function ord(ctakes one-character string as parameter and returns the integer code point for that character converselythe function chr(jtakes an integer and returns its associated one-character string in order to find replacement for character in our caesar cipherwe need to map the characters to to the respective numbers to the formula for doing that conversion is ord(corda as sanity checkif character is we have that when is we will find that its ordinal value is precisely one more than that for so their difference is in generalthe integer that results from such calculation can be used as an index into our precomputed translation stringas illustrated in figure encoder array using as an index in unicode ordt orda here is the replacement for figure illustrating the use of uppercase characters as indicesin this case to perform the replacement rule for caesar cipher encryption in code fragment we develop python class for performing the caesar cipher with an arbitrary rotational shiftand demonstrate its use when we run this program (to perform simple test)we get the following output secretwkh hdjoh lv lq sodbphhw dw mrh' messagethe eagle is in playmeet at joe' the constructor for the class builds the forward and backward translation strings for the given rotation with those in handthe encryption and decryption algorithms are essentially the sameand so we perform both by means of nonpublic utility method named transform |
21,872 | array-based sequences class caesarcipher """class for doing encryption and decryption using caesar cipher "" def init (selfshift) """construct caesar cipher using given integer shift for rotation ""temp array for encryption encoder [none temp array for decryption decoder [none for in range( ) encoder[kchr(( shift orda ) decoder[kchr(( shift orda )will store as string self forward join(encodersince fixed self backward join(decoder def encrypt(selfmessage) """return string representing encripted message "" return self transform(messageself forward def decrypt(selfsecret) """return decrypted message given encrypted secret "" return self transform(secretself backward def transform(selforiginalcode) """utility to perform transformation based on given code string "" msg list(original for in range(len(msg)) if msg[kisupper)index from to ord(msg[ ]orda msg[kcode[jreplace this character return join(msg if name =__main__ cipher caesarcipher( message "the eagle is in playmeet at joe coded cipher encrypt(message printsecretcoded answer cipher decrypt(coded printmessageanswercode fragment complete python class for the caesar cipher |
21,873 | multidimensional data sets liststuplesand strings in python are one-dimensional we use single index to access each element of the sequence many computer applications involve multidimensional data sets for examplecomputer graphics are often modeled in either two or three dimensions geographic information may be naturally represented in two dimensionsmedical imaging may provide three-dimensional scans of patientand company' valuation is often based upon high number of independent financial measures that can be modeled as multidimensional data two-dimensional array is sometimes also called matrix we may use two indicessay and jto refer to the cells in the matrix the first index usually refers to row number and the second to column numberand these are traditionally zeroindexed in computer science figure illustrates two-dimensional data set with integer values this data mightfor examplerepresent the number of stores in various regions of manhattan figure illustration of two-dimensional integer data setwhich has rows and columns the rows and columns are zero-indexed if this data set were named storesthe value of stores[ ][ is and the value of stores[ ][ is common representation for two-dimensional data set in python is as list of lists in particularwe can represent two-dimensional array as list of rowswith each row itself being list of values for examplethe two-dimensional data might be stored in python as follows data [ ][ ][ an advantage of this representation is that we can naturally use syntax such as data[ ][ to represent the value that has row index and column index as data[ ]the second entry in the outer listis itself listand thus indexable |
21,874 | constructing multidimensional list to quickly initialize one-dimensional listwe generally rely on syntax such as data [ to create list of zeros on page we emphasized that from technical perspectivethis creates list of length with all entries referencing the same integer instancebut that there was no meaningful consequence of such aliasing because of the immutability of the int class in python we have to be considerably more careful when creating list of lists if our goal were to create the equivalent of two-dimensional list of integerswith rows and columnsand to initialize all values to zeroa flawed approach might be to try the command data ([ cr warningthis is mistake while([ cis indeed list of zerosmultiplying that list by unfortunately creates single list with length cjust as [ , , results in list [ betteryet still flawed attempt is to make list that contains the list of zeros as its only elementand then to multiply that list by that iswe could try the command data [ cr warningstill mistake this is much closeras we actually do have structure that is formally list of lists the problem is that all entries of the list known as data are references to the same instance of list of zeros figure provides portrayal of such aliasing data figure flawed representation of data set as list of listscreated with the command data [ (for simplicitywe overlook the fact that the values in the secondary list are referential this is truly problem setting an entry such as data[ ][ would change the first entry of the secondary list to reference new value yet that cell of the secondary list also represents the value data[ ][ ]because "rowdata[ and "rowdata[ refer to the same secondary list |
21,875 | data figure valid representation of data set as list of lists (for simplicitywe overlook the fact that the values in the secondary lists are referential to properly initialize two-dimensional listwe must ensure that each cell of the primary list refers to an independent instance of secondary list this can be accomplished through the use of python' list comprehension syntax data [ for in range(rthis command produces valid configurationsimilar to the one shown in figure by using list comprehensionthe expression [ is reevaluated for each pass of the embedded for loop thereforewe get distinct secondary listsas desired (we note that the variable in that command is irrelevantwe simply need for loop that iterates times two-dimensional arrays and positional games many computer gamesbe they strategy gamessimulation gamesor first-person conflict gamesinvolve objects that reside in two-dimensional space software for such positional games need way of representing such two-dimensional "board,and in python the list of lists is natural choice tic-tac-toe as most school children knowtic-tac-toe is game played in three-by-three board two players-- and --alternate in placing their respective marks in the cells of this boardstarting with player if either player succeeds in getting three of his or her marks in rowcolumnor diagonalthen that player wins this is admittedly not sophisticated positional gameand it' not even that much fun to playsince good player can always force tie tic-tac-toe' saving grace is that it is nicesimple example showing how two-dimensional arrays can be used for positional games software for more sophisticated positional gamessuch as checkerschessor the popular simulation gamesare all based on the same approach we illustrate here for using two-dimensional array for tic-tac-toe |
21,876 | our representation of board will be list of lists of characterswith or designating player' moveor designating an empty space for examplethe board configuration will be stored internally as ] ] ]we develop complete python class for maintaining tic-tac-toe board for two players that class will keep track of the moves and report winnerbut it does not perform any strategy or allow someone to play tic-tac-toe against the computer the details of such program are beyond the scope of this but it might nonetheless make good course project (see exercise - before presenting the implementation of the classwe demonstrate its public interface with simple test in code fragment game tictactoex movesgame mark( )game mark( )game mark( )game mark( )game mark( movesgame mark( game mark( game mark( game mark( print(gamewinner game winnerif winner is noneprinttie elseprint(winnerwins code fragment simple test for our tic-tac-toe class the basic operations are that new game instance represents an empty boardthat the mark( ,jmethod adds mark at the given position for the current player (with the software managing the alternating of turns)and that the game board can be printed and the winner determined the complete source code for the tictactoe class is given in code fragment our mark method performs error checking to make sure that valid indices are sentthat the position is not already occupiedand that no further moves are made after someone wins the game |
21,877 | class tictactoe """management of tic-tac-toe game (does not do strategy"" def init (self) """start new game "" self board for in range( self player def mark(selfij) """put an or mark at position ( ,jfor next player turn "" if not ( < < and < < ) raise valueerrorinvalid board position if self board[ ][ ! raise valueerrorboard position occupied if self winneris not none raise valueerrorgame is already complete self board[ ][jself player if self player = self player else self player def is win(selfmark) """check whether the board configuration is win for the given player "" board self board local variable for shorthand return (mark =board[ ][ =board[ ][ =board[ ][ or row mark =board[ ][ =board[ ][ =board[ ][ or row mark =board[ ][ =board[ ][ =board[ ][ or row mark =board[ ][ =board[ ][ =board[ ][ or column mark =board[ ][ =board[ ][ =board[ ][ or column mark =board[ ][ =board[ ][ =board[ ][ or column mark =board[ ][ =board[ ][ =board[ ][ or diagonal mark =board[ ][ =board[ ][ =board[ ][ ]rev diag def winner(self) """return mark of winning playeror none to indicate tie "" for mark in xo if self is win(mark) return mark return none def str (self) """return string representation of current game board "" rows join(self board[ ]for in range( ) return \ \ join(rowscode fragment complete python class for managing tic-tac-toe game |
21,878 | exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - execute the experiment from code fragment and compare the results on your system to those we report in code fragment - in code fragment we perform an experiment to compare the length of python list to its underlying memory usage determining the sequence of array sizes requires manual inspection of the output of that program redesign the experiment so that the program outputs only those values of at which the existing capacity is exhausted for exampleon system consistent with the results of code fragment your program should output that the sequence of array capacities are - modify the experiment from code fragment in order to demonstrate that python' list class occasionally shrinks the size of its underlying array when elements are popped from list - our dynamicarray classas given in code fragment does not support use of negative indices with getitem update that method to better match the semantics of python list - redo the justification of proposition assuming that the the cost of growing the array from size to size is cyber-dollars how much should each append operation be charged to make the amortization workr- our implementation of insert for the dynamicarray classas given in code fragment has the following inefficiency in the case when resize occursthe resize operation takes time to copy all the elements from an old array to new arrayand then the subsequent loop in the body of insert shifts many of those elements give an improved implementation of the insert methodso thatin the case of resizethe elements are shifted into their final position during that operationthereby avoiding the subsequent shifting - let be an array of size > containing integers from to inclusivewith exactly one repeated describe fast algorithm for finding the integer in that is repeated - experimentally evaluate the efficiency of the pop method of python' list class when using varying indices as parameteras we did for insert on page report your results akin to table |
21,879 | - explain the changes that would have to be made to the program of code fragment so that it could perform the caesar cipher for messages that are written in an alphabet-based language other than englishsuch as greekrussianor hebrew - the constructor for the caesarcipher class in code fragment can be implemented with two-line body by building the forward and backward strings using combination of the join method and an appropriate comprehension syntax give such an implementation - use standard control structures to compute the sum of all numbers in an data setrepresented as list of lists - describe how the built-in sum function can be combined with python' comprehension syntax to compute the sum of all numbers in an data setrepresented as list of lists creativity - in the experiment of code fragment we begin with an empty list if data were initially constructed with nonempty lengthdoes this affect the sequence of values at which the underlying array is expandedperform your own experimentsand comment on any relationship you see between the initial length and the expansion sequence - the shuffle methodsupported by the random moduletakes python list and rearranges it so that every possible ordering is equally likely implement your own version of such function you may rely on the randrange(nfunction of the random modulewhich returns random number between and inclusive - consider an implementation of dynamic arraybut instead of copying the elements into an array of double the size (that isfrom to nwhen its capacity is reachedwe copy the elements into an array with / additional cellsgoing from capacity to capacity / prove that performing sequence of append operations still runs in (ntime in this case - implement pop method for the dynamicarray classgiven in code fragment that removes the last element of the arrayand that shrinks the capacitynof the array by half any time the number of elements in the array goes below / - prove that when using dynamic array that grows and shrinks as in the previous exercisethe following series of operations takes (ntimen append operations on an initially empty arrayfollowed by pop operations |
21,880 | array-based sequences - give formal proof that any sequence of append or pop operations on an initially empty dynamic array takes (ntimeif using the strategy described in exercise - - consider variant of exercise - in which an array of capacity is resized to capacity precisely that of the number of elementsany time the number of elements in the array goes strictly below / give formal proof that any sequence of append or pop operations on an initially empty dynamic array takes (ntime - consider variant of exercise - in which an array of capacity nis resized to capacity precisely that of the number of elementsany time the number of elements in the array goes strictly below / show that there exists sequence of operations that requires ( time to execute - in section we described four different ways to compose long string( repeated concatenation( appending to temporary list and then joining( using list comprehension with joinand ( using generator comprehension with join develop an experiment to test the efficiency of all four of these approaches and report your findings - develop an experiment to compare the relative efficiency of the extend method of python' list class versus using repeated calls to append to accomplish the equivalent task - based on the discussion of page develop an experiment to compare the efficiency of python' list comprehension syntax versus the construction of list by means of repeated calls to append - perform experiments to evaluate the efficiency of the remove method of python' list classas we did for insert on page use known values so that all removals occur either at the beginningmiddleor end of the list report your results akin to table - the syntax data remove(valuefor python list data removes only the first occurrence of element value from the list give an implementation of functionwith signature remove all(datavalue)that removes all occurrences of value from the given listsuch that the worst-case running time of the function is (non list with elements not that it is not efficient enough in general to rely on repeated calls to remove - let be an array of size > containing integers from to inclusivewith exactly five repeated describe good algorithm for finding the five integers in that are repeated - given python list of positive integerseach represented with log bitsdescribe an ( )-time method for finding -bit integer not in - argue why any solution to the previous problem must run in (ntime |
21,881 | - useful operation in databases is the natural join if we view database as list of ordered pairs of objectsthen the natural join of databases and is the list of all ordered triples (xyzsuch that the pair (xyis in and the pair (yzis in describe and analyze an efficient algorithm for computing the natural join of list of pairs and list of pairs - when bob wants to send alice message on the internethe breaks into data packetsnumbers the packets consecutivelyand injects them into the network when the packets arrive at alice' computerthey may be out of orderso alice must assemble the sequence of packets in order before she can be sure she has the entire message describe an efficient scheme for alice to do thisassuming that she knows the value of what is the running time of this algorithmc- describe way to use recursion to add all the numbers in an data setrepresented as list of lists projects - write python function that takes two three-dimensional numeric data sets and adds them componentwise - write python program for matrix class that can add and multiply twodimensional arrays of numbersassuming the dimensions agree appropriately for the operation - write program that can perform the caesar cipher for english messages that include both upperand lowercase characters - implement classsubstitutioncipherwith constructor that takes string with the uppercase letters in an arbitrary order and uses that for the forward mapping for encryption (akin to the self forward string in our caesarcipher class of code fragment you should derive the backward mapping from the forward version - redesign the caesarcipher class as subclass of the substitutioncipher from the previous problem - design randomcipher class as subclass of the substitutioncipher from exercise - so that each instance of the class relies on random permutation of letters for its mapping notes the fundamental data structures of arrays belong to the folklore of computer science they were first chronicled in the computer science literature by knuth in his seminal book on fundamental algorithms [ |
21,882 | stacksqueuesand deques contents stacks the stack abstract data type simple array-based stack implementation reversing data using stack matching parentheses and html tags queues the queue abstract data type array-based queue implementation double-ended queues the deque abstract data type implementing deque with circular array deques in the python collections module exercises |
21,883 | stacks stack is collection of objects that are inserted and removed according to the last-infirst-out (lifoprinciple user may insert objects into stack at any timebut may only access or remove the most recently inserted object that remains (at the so-called "topof the stackthe name "stackis derived from the metaphor of stack of plates in spring-loadedcafeteria plate dispenser in this casethe fundamental operations involve the "pushingand "poppingof plates on the stack when we need new plate from the dispenserwe "popthe top plate off the stackand when we add platewe "pushit down on the stack to become the new top plate perhaps an even more amusing example is pez (rcandy dispenserwhich stores mint candies in spring-loaded container that "popsout the topmost candy in the stack when the top of the dispenser is lifted (see figure stacks are fundamental data structure they are used in many applicationsincluding the following example internet web browsers store the addresses of recently visited sites in stack each time user visits new sitethat site' address is "pushedonto the stack of addresses the browser then allows the user to "popback to previously visited sites using the "backbutton example text editors usually provide an "undomechanism that cancels recent editing operations and reverts to former states of document this undo operation can be accomplished by keeping text changes in stack figure schematic drawing of pez (rdispensera physical implementation of the stack adt (pez (ris registered trademark of pez candyinc |
21,884 | the stack abstract data type stacks are the simplest of all data structuresyet they are also among the most important they are used in host of different applicationsand as tool for many more sophisticated data structures and algorithms formallya stack is an abstract data type (adtsuch that an instance supports the following two methodss push( )add element to the top of stack pop)remove and return the top element from the stack san error occurs if the stack is empty additionallylet us define the following accessor methods for conveniences top)return reference to the top element of stack swithout removing itan error occurs if the stack is empty is empty)return true if stack does not contain any elements len( )return the number of elements in stack sin pythonwe implement this with the special method len by conventionwe assume that newly created stack is emptyand that there is no priori bound on the capacity of the stack elements added to the stack can have arbitrary type example the following table shows series of stack operations and their effects on an initially empty stack of integers operation push( push( len(ss pops is emptys pops is emptys pops push( push( tops push( len(ss pops push( push( popreturn value false true "error stack contents [ [ [ [ [ [[[[ [ [ [ [ [ [ [ [ |
21,885 | simple array-based stack implementation we can implement stack quite easily by storing its elements in python list the list class already supports adding an element to the end with the append methodand removing the last element with the pop methodso it is natural to align the top of the stack at the end of the listas shown in figure top figure implementing stack with python liststoring the top element in the rightmost cell although programmer could directly use the list class in place of formal stack classlists also include behaviors ( adding or removing elements from arbitrary positionsthat would break the abstraction that the stack adt represents alsothe terminology used by the list class does not precisely align with traditional nomenclature for stack adtin particular the distinction between append and push insteadwe demonstrate how to use list for internal storage while providing public interface consistent with stack the adapter pattern the adapter design pattern applies to any context where we effectively want to modify an existing class so that its methods match those of relatedbut differentclass or interface one general way to apply the adapter pattern is to define new class in such way that it contains an instance of the existing class as hidden fieldand then to implement each method of the new class using methods of this hidden instance variable by applying the adapter pattern in this waywe have created new class that performs some of the same functions as an existing classbut repackaged in more convenient way in the context of the stack adtwe can adapt python' list class using the correspondences shown in table stack method push(es pops tops is emptylen(srealization with python list append(el popl[- len( = len(ltable realization of stack as an adaptation of python list |
21,886 | implementing stack using python list we use the adapter design pattern to define an arraystack class that uses an underlying python list for storage (we choose the name arraystack to emphasize that the underlying storage is inherently array based one question that remains is what our code should do if user calls pop or top when the stack is empty our adt suggests that an error occursbut we must decide what type of error when pop is called on an empty python listit formally raises an indexerroras lists are index-based sequences that choice does not seem appropriate for stacksince there is no assumption of indices insteadwe can define new exception class that is more appropriate code fragment defines such an empty class as trivial subclass of the python exception class class empty(exception)"""error attempting to access an element from an empty container ""pass code fragment definition for an empty exception class the formal definition for our arraystack class is given in code fragment the constructor establishes the member self data as an initially empty python listfor internal storage the rest of the public stack behaviors are implementedusing the corresponding adaptation that was outlined in table example usage belowwe present an example of the use of our arraystack classmirroring the operations at the beginning of example on page arraystacks push( push( print(len( )print( pop)print( is empty)print( pop)print( is empty) push( push( print( top) push( print(len( )print( pop) push( contentscontents[ contents[ contents[ ]contents[ ]contents[ ]contents]contents]contents[ contents[ contents[ ]contents[ contents[ ]contents[ ]contents[ outputs outputs outputs false outputs outputs true outputs outputs outputs |
21,887 | class arraystack """lifo stack implementation using python list as underlying storage "" def init (self) """create an empty stack ""nonpublic list instance self data def len (self) """return the number of elements in the stack "" return len(self data def is empty(self) """return true if the stack is empty "" return len(self data= def push(selfe) """add element to the top of the stack ""new item stored at end of list self data append( def top(self) """return (but do not removethe element at the top of the stack raise empty exception if the stack is empty "" if self is empty) raise emptystack is empty the last item in the list return self data[- def pop(self) """remove and return the element from the top of the stack ( lifo raise empty exception if the stack is empty "" if self is empty) raise emptystack is empty remove last item from list return self data popcode fragment implementing stack using python list as storage |
21,888 | analyzing the array-based stack implementation table shows the running times for our arraystack methods the analysis directly mirrors the analysis of the list class given in section the implementations for topis emptyand len use constant time in the worst case the ( time for push and pop are amortized bounds (see section ) typical call to either of these methods uses constant timebut there is occasionally an ( )-time worst casewhere is the current number of elements in the stackwhen an operation causes the list to resize its internal array the space usage for stack is (noperation push(es pops tops is emptylen(samortized running time ( ) ( ) ( ( ( table performance of our array-based stack implementation the bounds for push and pop are amortized due to similar bounds for the list class the space usage is ( )where is the current number of elements in the stack avoiding amortization by reserving capacity in some contextsthere may be additional knowledge that suggests maximum size that stack will reach our implementation of arraystack from code fragment begins with an empty list and expands as needed in the analysis of lists from section we emphasized that it is more efficient in practice to construct list with initial length than it is to start with an empty list and append items (even though both approaches run in (ntimeas an alternate model for stackwe might wish for the constructor to accept parameter specifying the maximum capacity of stack and to initialize the data member to list of that length implementing such model requires significant changes relative to code fragment the size of the stack would no longer be synonymous with the length of the listand pushes and pops of the stack would not require changing the length of the list insteadwe suggest maintaining separate integer as an instance variable that denotes the current number of elements in the stack details of such an implementation are left as exercise - |
21,889 | reversing data using stack as consequence of the lifo protocola stack can be used as general tool to reverse data sequence for exampleif the values and are pushed onto stack in that orderthey will be popped from the stack in the order and then this idea can be applied in variety of settings for examplewe might wish to print lines of file in reverse order in order to display data set in decreasing order rather than increasing order this can be accomplished by reading each line and pushing it onto stackand then writing the lines in the order they are popped an implementation of such process is given in code fragment def reverse file(filename) """overwrite given file with its contents line-by-line reversed "" arraystack original open(filename for line in originalwe will re-insert newlines when writing push(line rstrip\ ) original close now we overwrite with contents in lifo order reopening file overwrites original output open(filenamew while not is empty) output write( pop\ re-insert newline characters output closecode fragment function that reverses the order of lines in file one technical detail worth noting is that we intentionally strip trailing newlines from lines as they are readand then re-insert newlines after each line when writing the resulting file our reason for doing this is to handle special case in which the original file does not have trailing newline for the final line if we exactly echoed the lines read from the file in reverse orderthen the original last line would be followed (without newlineby the original second-to-last line in our implementationwe ensure that there will be separating newline in the result the idea of using stack to reverse data set can be applied to other types of sequences for exampleexercise - explores the use of stack to provide yet another solution for reversing the contents of python list ( recursive solution for this goal was discussed in section more challenging task is to reverse the order in which elements are stored within stack if we were to move them from one stack to anotherthey would be reversedbut if we were to then replace them into the original stackthey would be reversed againthereby reverting to their original order exercise - explores solution for this task |
21,890 | matching parentheses and html tags in this subsectionwe explore two related applications of stacksboth of which involve testing for pairs of matching delimiters in our first applicationwe consider arithmetic expressions that may contain various pairs of grouping symbolssuch as parentheses"(and ")braces"{and "}brackets"[and "]each opening symbol must match its corresponding closing symbol for examplea left bracket"[,must match corresponding right bracket"],as in the expression [( + )-( + )the following examples further illustrate this conceptcorrect)()){([)])correct(()()){([)])})incorrect)()){([)])incorrect({])incorrectwe leave the precise definition of matching group of symbols to exercise - an algorithm for matching delimiters an important task when processing arithmetic expressions is to make sure their delimiting symbols match up correctly code fragment presents python implementation of such an algorithm discussion of the code follows def is matched(expr) """return true if all delimiters are properly matchfalse otherwise ""opening delimiters lefty ({respective closing delims righty )} arraystack for in expr if in lefty push(cpush left delimiter on stack elif in righty if is empty) return false nothing to match with if righty index( !lefty index( pop)) return false mismatched were all symbols matched return is emptycode fragment function for matching delimiters in an arithmetic expression |
21,891 | we assume the input is sequence of characterssuch as [( + )-( + )we perform left-to-right scan of the original sequenceusing stack to facilitate the matching of grouping symbols each time we encounter an opening symbolwe push that symbol onto sand each time we encounter closing symbolwe pop symbol from the stack (assuming is not empty)and check that these two symbols form valid pair if we reach the end of the expression and the stack is emptythen the original expression was properly matched otherwisethere must be an opening delimiter on the stack without matching symbol if the length of the original expression is nthe algorithm will make at most calls to push and calls to pop those calls run in total of (ntimeeven considering the amortized nature of the ( time bound for those methods given that our selection of possible delimiters({[has constant sizeauxiliary tests such as in lefty and righty index(ceach run in ( time combining these operationsthe matching algorithm on sequence of length runs in (ntime matching tags in markup language another application of matching delimiters is in the validation of markup languages such as html or xml html is the standard format for hyperlinked documents on the internet and xml is an extensible markup language used for variety of structured data sets we show sample html document and possible rendering in figure the little boat the storm tossed the little boat like cheap sneaker in an old washing machine the three drunken fishermen were used to such treatmentof coursebut not the tree salesmanwho even as stowaway now felt that he had overpaid for the voyage will the salesman diewhat color is the boatand what about naomi(athe little boat the storm tossed the little boat like cheap sneaker in an old washing machine the three drunken fishermen were used to such treatmentof coursebut not the tree salesmanwho even as stowaway now felt that he had overpaid for the voyage will the salesman die what color is the boat and what about naomi(bfigure illustrating html tags (aan html document(bits rendering |
21,892 | in an html documentportions of text are delimited by html tags simple opening html tag has the form "and the corresponding closing tag has the form "for examplewe see the tag on the first line of figure ( )and the matching tag at the close of that document other commonly used html tags that are used in this example includebodydocument body section header centercenter justify pparagraph olnumbered (orderedlist lilist item ideallyan html document should have matching tagsalthough most browsers tolerate certain number of mismatching tags in code fragment we give python function that matches tags in string representing an html document we make left-to-right pass through the raw stringusing index to track our progress and the find method of the str class to locate the characters that define the tags opening tags are pushed onto the stackand matched against closing tags as they are popped from the stackjust as we did when matching delimiters in code fragment by similar analysisthis algorithm runs in (ntimewhere is the number of characters in the raw html source def is matched html(raw) """return true if all html tags are properly matchfalse otherwise "" arraystackfind first '<character (if any raw find while !- find next '>character raw findj+ if =- return false invalid tag tag raw[ + :kstrip away this is opening tag if not tag startswith) push(tag elsethis is closing tag if is empty) return false nothing to match with if tag[ :! pop) return false mismatched delimiter find next '<character (if any raw findk+ were all opening tags matched return is emptycode fragment function for testing if an html document has matching tags |
21,893 | queues another fundamental data structure is the queue it is close "cousinof the stackas queue is collection of objects that are inserted and removed according to the first-infirst-out (fifoprinciple that iselements can be inserted at any timebut only the element that has been in the queue the longest can be next removed we usually say that elements enter queue at the back and are removed from the front metaphor for this terminology is line of people waiting to get on an amusement park ride people waiting for such ride enter at the back of the line and get on the ride from the front of the line there are many other applications of queues (see figure storestheatersreservation centersand other similar services typically process customer requests according to the fifo principle queue would therefore be logical choice for data structure to handle calls to customer service centeror wait-list at restaurant fifo queues are also used by many computing devicessuch as networked printeror web server responding to requests tickets (aer ent all call queue (bfigure real-world examples of first-infirst-out queue (apeople waiting in line to purchase tickets(bphone calls being routed to customer service center |
21,894 | the queue abstract data type formallythe queue abstract data type defines collection that keeps objects in sequencewhere element access and deletion are restricted to the first element in the queueand element insertion is restricted to the back of the sequence this restriction enforces the rule that items are inserted and deleted in queue according to the first-infirst-out (fifoprinciple the queue abstract data type (adtsupports the following two fundamental methods for queue qq enqueue( )add element to the back of queue dequeue)remove and return the first element from queue qan error occurs if the queue is empty the queue adt also includes the following supporting methods (with first being analogous to the stack' top method) first)return reference to the element at the front of queue qwithout removing itan error occurs if the queue is empty is empty)return true if queue does not contain any elements len( )return the number of elements in queue qin pythonwe implement this with the special method len by conventionwe assume that newly created queue is emptyand that there is no priori bound on the capacity of the queue elements added to the queue can have arbitrary type example the following table shows series of queue operations and their effects on an initially empty queue of integers operation enqueue( enqueue( len(qq dequeueq is emptyq dequeueq is emptyq dequeueq enqueue( enqueue( firstq enqueue( len(qq dequeuereturn value false true "error first last [ [ [ [ [ [[[[ [ [ [ [ [ |
21,895 | array-based queue implementation for the stack adtwe created very simple adapter class that used python list as the underlying storage it may be very tempting to use similar approach for supporting the queue adt we could enqueue element by calling append(eto add it to the end of the list we could use the syntax pop( )as opposed to pop)to intentionally remove the first element from the list when dequeuing as easy as this would be to implementit is tragically inefficient as we discussed in section when pop is called on list with non-default indexa loop is executed to shift all elements beyond the specified index to the leftso as to fill the hole in the sequence caused by the pop thereforea call to pop( always causes the worst-case behavior of th(ntime we can improve on the above strategy by avoiding the call to pop( entirely we can replace the dequeued entry in the array with reference to noneand maintain an explicit variable to store the index of the element that is currently at the front of the queue such an algorithm for dequeue would run in ( time after several dequeue operationsthis approach might lead to the configuration portrayed in figure figure allowing the front of the queue to drift away from index unfortunatelythere remains drawback to the revised approach in the case of stackthe length of the list was precisely equal to the size of the stack (even if the underlying array for the list was slightly largerwith the queue design that we are consideringthe situation is worse we can build queue that has relatively few elementsyet which are stored in an arbitrarily large list this occursfor exampleif we repeatedly enqueue new element and then dequeue another (allowing the front to drift rightwardover timethe size of the underlying list would grow to (mwhere is the total number of enqueue operations since the creation of the queuerather than the current number of elements in the queue this design would have detrimental consequences in applications in which queues have relatively modest sizebut which are used for long periods of time for examplethe wait-list for restaurant might never have more than entries at one timebut over the course of day (or week)the overall number of entries would be significantly larger |
21,896 | using an array circularly in developing more robust queue implementationwe allow the front of the queue to drift rightwardand we allow the contents of the queue to "wrap aroundthe end of an underlying array we assume that our underlying array has fixed length that is greater that the actual number of elements in the queue new elements are enqueued toward the "endof the current queueprogressing from the front to index and continuing at index then figure illustrates such queue with first element and last element - figure modeling queue with circular array that wraps around the end implementing this circular view is not difficult when we dequeue an element and want to "advancethe front indexwe use the arithmetic ( recall that the operator in python denotes the modulo operatorwhich is computed by taking the remainder after an integral division for example divided by has quotient of with remainder that is so in python / evaluates to the quotient while evaluates to the remainder the modulo operator is ideal for treating an array circularly as concrete exampleif we have list of length and front index we can advance the front by formally computing ( + which is simply as divided by is with remainder of similarlyadvancing index results in index but when we advance from index (the last one in the array)we compute ( + which evaluates to index (as divided by has remainder of zeroa python queue implementation complete implementation of queue adt using python list in circular fashion is presented in code fragments and internallythe queue class maintains the following three instance variablesdatais reference to list instance with fixed capacity sizeis an integer representing the current number of elements stored in the queue (as opposed to the length of the data listfrontis an integer that represents the index within data of the first element of the queue (assuming the queue is not emptywe initially reserve list of moderate size for storing dataalthough the queue formally has size zero as technicalitywe initialize the front index to zero when front or dequeue are called with no elements in the queuewe raise an instance of the empty exceptiondefined in code fragment for our stack |
21,897 | class arrayqueue """fifo queue implementation using python list as underlying storage ""moderate capacity for all new queues default capacity def init (self) """create an empty queue "" self data [nonearrayqueue default capacity self size self front def len (self) """return the number of elements in the queue "" return self size def is empty(self) """return true if the queue is empty "" return self size = def first(self) """return (but do not removethe element at the front of the queue raise empty exception if the queue is empty "" if self is empty) raise emptyqueue is empty return self data[self front def dequeue(self) """remove and return the first element of the queue ( fifo raise empty exception if the queue is empty "" if self is empty) raise emptyqueue is empty answer self data[self fronthelp garbage collection self data[self frontnone self front (self front len(self data self size - return answer code fragment array-based implementation of queue (continued in code fragment |
21,898 | def enqueue(selfe)"""add an element to the back of queue ""if self size =len(self data)double the array size self resize( len(self data)avail (self front self sizelen(self dataself data[availe self size + we assume cap >len(selfdef resize(selfcap)"""resize to new list of capacity >len(self""keep track of existing list old self data allocate list with new capacity self data [nonecap walk self front only consider existing elements for in range(self size)intentionally shift indices self data[kold[walkwalk ( walklen(olduse old size as modulus front has been realigned self front code fragment array-based implementation of queue (continued from code fragment the implementation of len and is empty are trivialgiven knowledge of the size the implementation of the front method is also simpleas the front index tells us precisely where the desired element is located within the data listassuming that list is not empty adding and removing elements the goal of the enqueue method is to add new element to the back of the queue we need to determine the proper index at which to place the new element although we do not explicitly maintain an instance variable for the back of the queuewe compute the location of the next opening based on the formulaavail (self front self sizelen(self datanote that we are using the size of the queue as it exists prior to the addition of the new element for exampleconsider queue with capacity current size and first element at index the three elements of such queue are stored at indices and the new element should be placed at index (front size in case with wrap-aroundthe use of the modular arithmetic achieves the desired circular semantics for exampleif our hypothetical queue had elements with the first at index our computation of ( + evaluates to which is perfect since the three existing elements occupy indices and |
21,899 | when the dequeue method is calledthe current value of self front designates the index of the value that is to be removed and returned we keep local reference to the element that will be returnedsetting answer self data[self frontjust prior to removing the reference to that object from the listwith the assignment self data[self frontnone our reason for the assignment to none relates to python' mechanism for reclaiming unused space internallypython maintains count of the number of references that exist to each object if that count reaches zerothe object is effectively inaccessiblethus the system may reclaim that memory for future use (for more detailssee section since we are no longer responsible for storing dequeued elementwe remove the reference to it from our list so as to reduce that element' reference count the second significant responsibility of the dequeue method is to update the value of front to reflect the removal of the elementand the presumed promotion of the second element to become the new first in most caseswe simply want to increment the index by onebut because of the possibility of wrap-around configurationwe rely on modular arithmetic as originally described on page resizing the queue when enqueue is called at time when the size of the queue equals the size of the underlying listwe rely on standard technique of doubling the storage capacity of the underlying list in this wayour approach is similar to the one used when we implemented dynamicarray in section howevermore care is needed in the queue' resize utility than was needed in the corresponding method of the dynamicarray class after creating temporary reference to the old list of valueswe allocate new list that is twice the size and copy references from the old list to the new list while transferring the contentswe intentionally realign the front of the queue with index in the new arrayas shown in figure this realignment is not purely cosmetic since the modular arithmetic depends on the size of the arrayour state would be flawed had we transferred each element to its same index in the new array = figure resizing the queuewhile realigning the front element with index |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.