id
int64
0
25.6k
text
stringlengths
0
4.59k
12,900
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
12,901
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 [
12,902
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
12,903
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
12,904
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
12,905
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(
12,906
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
12,907
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
12,908
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
12,909
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
12,910
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
12,911
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
12,912
- 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
12,913
- 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 [
12,914
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
12,915
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
12,916
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
12,917
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
12,918
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
12,919
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
12,920
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
12,921
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
12,922
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
12,923
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
12,924
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
12,925
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
12,926
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
12,927
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
12,928
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
12,929
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
12,930
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
12,931
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 -
12,932
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
12,933
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
12,934
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
12,935
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
12,936
- 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
12,937
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
12,938
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
12,939
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
12,940
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)
12,941
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
12,942
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
12,943
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
12,944
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
12,945
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
12,946
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
12,947
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
12,948
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
12,949
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
12,950
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
12,951
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
12,952
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
12,953
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
12,954
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
12,955
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
12,956
- 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
12,957
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
12,958
- 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 [
12,959
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
12,960
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
12,961
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 [ [ [ [ [ [[[[ [ [ [ [ [ [ [ [
12,962
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
12,963
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
12,964
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
12,965
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 -
12,966
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
12,967
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
12,968
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
12,969
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
12,970
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
12,971
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 [ [ [ [ [ [[[[ [ [ [ [ [
12,972
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
12,973
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
12,974
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
12,975
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
12,976
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
12,977
shrinking the underlying array desirable property of queue implementation is to have its space usage be th(nwhere is the current number of elements in the queue our arrayqueue implementationas given in code fragments and does not have this property it expands the underlying array when enqueue is called with the queue at full capacitybut the dequeue implementation never shrinks the underlying array as consequencethe capacity of the underlying array is proportional to the maximum number of elements that have ever been stored in the queuenot the current number of elements we discussed this very issue on page in the context of dynamic arraysand in subsequent exercises - through - of that robust approach is to reduce the array to half of its current sizewhenever the number of elements stored in it falls below one fourth of its capacity we can implement this strategy by adding the following two lines of code in our dequeue methodjust after reducing self size at line of code fragment to reflect the loss of an element if self size len(self data/ self resize(len(self data/ analyzing the array-based queue implementation table describes the performance of our array-based implementation of the queue adtassuming the improvement described above for occasionally shrinking the size of the array with the exception of the resize utilityall of the methods rely on constant number of statements involving arithmetic operationscomparisonsand assignments thereforeeach method runs in worst-case ( timeexcept for enqueue and dequeuewhich have amortized bounds of ( timefor reasons similar to those given in section operation enqueue(eq dequeueq firstq is emptylen(qamortized running time ( ) ( ) ( ( ( table performance of an array-based implementation of queue the bounds for enqueue and dequeue are amortized due to the resizing of the array the space usage is ( )where is the current number of elements in the queue
12,978
double-ended queues we next consider queue-like data structure that supports insertion and deletion at both the front and the back of the queue such structure is called doubleended queueor dequewhich is usually pronounced "deckto avoid confusion with the dequeue method of the regular queue adtwhich is pronounced like the abbreviation " the deque abstract data type is more general than both the stack and the queue adts the extra generality can be useful in some applications for examplewe described restaurant using queue to maintain waitlist occassionallythe first person might be removed from the queue only to find that table was not availabletypicallythe restaurant will re-insert the person at the first position in the queue it may also be that customer at the end of the queue may grow impatient and leave the restaurant (we will need an even more general data structure if we want to model customers leaving the queue from other positions the deque abstract data type to provide symmetrical abstractionthe deque adt is defined so that deque supports the following methodsd add first( )add element to the front of deque add last( )add element to the back of deque delete first)remove and return the first element from deque dan error occurs if the deque is empty delete last)remove and return the last element from deque dan error occurs if the deque is empty additionallythe deque adt will include the following accessorsd first)return (but do not removethe first element of deque dan error occurs if the deque is empty last)return (but do not removethe last element of deque dan error occurs if the deque is empty is empty)return true if deque does not contain any elements len( )return the number of elements in deque din pythonwe implement this with the special method len
12,979
example the following table shows series of operations and their effects on an initially empty deque of integers operation add last( add first( add first( firstd delete lastlen(dd delete lastd delete lastd add first( lastd add first( is emptyd lastreturn value false deque [ [ [ [ [ [ [ [[ [ [ [ [ implementing deque with circular array we can implement the deque adt in much the same way as the arrayqueue class provided in code fragments and of section (so much so that we leave the details of an arraydeque implementation to exercise - we recommend maintaining the same three instance variablesdatasizeand front whenever we need to know the index of the back of the dequeor the first available slot beyond the back of the dequewe use modular arithmetic for the computation for exampleour implementation of the lastmethod uses the index back (self front self size len(self dataour implementation of the arraydeque add last method is essentially the same as that for arrayqueue enqueueincluding the reliance on resize utility likewisethe implementation of the arraydeque delete first method is the same as arrayqueue dequeue implementations of add first and delete last use similar techniques one subtlety is that call to add first may need to wrap around the beginning of the arrayso we rely on modular arithmetic to circularly decrement the indexas self front (self front len(self datacyclic shift the efficiency of an arraydeque is similar to that of an arrayqueuewith all operations having ( running timebut with that bound being amortized for operations that may change the size of the underlying list
12,980
deques in the python collections module an implementation of deque class is available in python' standard collections module summary of the most commonly used behaviors of the collections deque class is given in table it uses more asymmetric nomenclature than our adt our deque adt len(dd add firstd add lastd delete firstd delete lastd firstd lastcollections deque len(dd appendleftd appendd popleftd popd[ [- [jd[jval cleard rotate(kd remove(ed count(edescription number of elements add to beginning add to end remove from beginning remove from end access first element access last element access arbitrary entry by index modify arbitrary entry by index clear all contents circularly shift rightward steps remove first matching element count number of matches for table comparison of our deque adt and the collections deque class the collections deque interface was chosen to be consistent with established naming conventions of python' list classfor which append and pop are presumed to act at the end of the list thereforeappendleft and popleft designate an operation at the beginning of the list the library deque also mimics list in that it is an indexed sequenceallowing arbitrary access or modification using the [jsyntax the library deque constructor also supports an optional maxlen parameter to force fixed-length deque howeverif call to append at either end is invoked when the deque is fullit does not throw an errorinsteadit causes one element to be dropped from the opposite side that iscalling appendleft when the deque is full causes an implicit pop from the right side to make room for the new element the current python distribution implements collections deque with hybrid approach that uses aspects of circular arraysbut organized into blocks that are themselves organized in doubly linked list ( data structure that we will introduce in the next the deque class is formally documented to guarantee ( )-time operations at either endbut ( )-time worst-case operations when using index notation near the middle of the deque
12,981
exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - what values are returned during the following series of stack operationsif executed upon an initially empty stackpush( )push( )pop()push( )push( )pop()pop()push( )push( )pop()push( )push( )pop()pop()push( )pop()pop( - suppose an initially empty stack has executed total of push operations top operationsand pop operations of which raised empty errors that were caught and ignored what is the current size of sr- implement function with signature transfer(stthat transfers all elements from stack onto stack tso that the element that starts at the top of is the first to be inserted onto tand the element at the bottom of ends up at the top of - give recursive method for removing all the elements from stack - implement function that reverses list of elements by pushing them onto stack in one orderand writing them back to the list in reversed order - give precise and complete definition of the concept of matching for grouping symbols in an arithmetic expression your definition may be recursive - what values are returned during the following sequence of queue operationsif executed on an initially empty queueenqueue( )enqueue( )dequeue()enqueue( )enqueue( )dequeue()dequeue()enqueue( )enqueue( )dequeue()enqueue( )enqueue( )dequeue()dequeue()enqueue( )dequeue()dequeue( - suppose an initially empty queue has executed total of enqueue operations first operationsand dequeue operations of which raised empty errors that were caught and ignored what is the current size of qr- had the queue of the previous problem been an instance of arrayqueue that used an initial array of capacity and had its size never been greater than what would be the final value of the front instance variabler- consider what happens if the loop in the arrayqueue resize method at lines - of code fragment had been implemented asfor in range(self size)self data[kold[krather than old[walkgive clear explanation of what could go wrong
12,982
- give simple adapter that implements our queue adt while using collections deque instance for storage - what values are returned during the following sequence of deque adt operationson initially empty dequeadd first( )add last( )add last( )add first( )back)delete first)delete last)add last( )first)last)add last( )delete first)delete firstr- suppose you have deque containing the numbers ( )in this order suppose further that you have an initially empty queue give code fragment that uses only and (and no other variablesand results in storing the elements in the order ( - repeat the previous problem using the deque and an initially empty stack creativity - suppose alice has picked three distinct integers and placed them into stack in random order write shortstraight-line piece of pseudo-code (with no loops or recursionthat uses only one comparison and only one variable xyet that results in variable storing the largest of alice' three integers with probability / argue why your method is correct - modify the arraystack implementation so that the stack' capacity is limited to maxlen elementswhere maxlen is an optional parameter to the constructor (that defaults to noneif push is called when the stack is at full capacitythrow full exception (defined similarly to emptyc- in the previous exercisewe assume that the underlying list is initially empty redo that exercisethis time preallocating an underlying list with length equal to the stack' maximum capacity - show how to use the transfer functiondescribed in exercise - and two temporary stacksto replace the contents of given stack with those same elementsbut in reversed order - in code fragment we assume that opening tags in html have form as with more generallyhtml allows optional attributes to be expressed as part of an opening tag the general form used is for examplea table can be given border and additional padding by using an opening tag of modify code fragment so that it can properly match tagseven when an opening tag may include one or more such attributes - describe nonrecursive algorithm for enumerating all permutations of the numbers { nusing an explicit stack
12,983
stacksqueuesand deques - show how to use stack and queue to generate all possible subsets of an -element set nonrecursively - postfix notation is an unambiguous way of writing an arithmetic expression without parentheses it is defined so that if "(exp op (exp )is normalfully parenthesized expression whose operation is opthe postfix version of this is "pexp pexp op"where pexp is the postfix version of exp and pexp is the postfix version of exp the postfix version of single number or variable is just that number or variable for examplethe postfix version of "(( ( ))/ is " /describe nonrecursive way of evaluating an expression in postfix notation - suppose you have three nonempty stacks rsand describe sequence of operations that results in storing all elements originally in below all of ' original elementswith both sets of those elements in their original order the final configuration for should be the same as its original configuration for exampleif [ ] [ ]and [ ]the final configuration should have [ and [ - describe how to implement the stack adt using single queue as an instance variableand only constant additional local memory within the method bodies what is the running time of the push()pop()and top(methods for your designc- describe how to implement the queue adt using two stacks as instance variablessuch that all queue operations execute in amortized ( time give formal proof of the amortized bound - describe how to implement the double-ended queue adt using two stacks as instance variables what are the running times of the methodsc- suppose you have stack containing elements and queue that is initially empty describe how you can use to scan to see if it contains certain element xwith the additional constraint that your algorithm must return the elements back to in their original order you may only use sqand constant number of other variables - modify the arrayqueue implementation so that the queue' capacity is limited to maxlen elementswhere maxlen is an optional parameter to the constructor (that defaults to noneif enqueue is called when the queue is at full capacitythrow full exception (defined similarly to emptyc- in certain applications of the queue adtit is common to repeatedly dequeue an elementprocess it in some wayand then immediately enqueue the same element modify the arrayqueue implementation to include rotatemethod that has semantics identical to the combinationq enqueue( dequeue)howeveryour implementation should be more efficient than making two separate calls (for examplebecause there is no need to modify size
12,984
- alice has two queuesq and rwhich can store integers bob gives alice odd integers and even integers and insists that she store all integers in and they then play game where bob picks or at random and then applies the round-robin schedulerdescribed in the to the chosen queue random number of times if the last number to be processed at the end of this game was oddbob wins otherwisealice wins how can alice allocate integers to queues to optimize her chances of winningwhat is her chance of winningc- suppose bob has four cows that he wants to take across bridgebut only one yokewhich can hold up to two cowsside by sidetied to the yoke the yoke is too heavy for him to carry across the bridgebut he can tie (and untiecows to it in no time at all of his four cowsmazie can cross the bridge in minutesdaisy can cross it in minutescrazy can cross it in minutesand lazy can cross it in minutes of coursewhen two cows are tied to the yokethey must go at the speed of the slower cow describe how bob can get all his cows across the bridge in minutes projects - give complete arraydeque implementation of the double-ended queue adt as sketched in section - give an array-based implementation of double-ended queue supporting all of the public behaviors shown in table for the collections deque classincluding use of the maxlen optional parameter when lengthlimited deque is fullprovide semantics similar to the collections deque classwhereby call to insert an element on one end of deque causes an element to be lost from the opposite side - implement program that can input an expression in postfix notation (see exercise - and output its value - the introduction of section notes that stacks are often used to provide "undosupport in applications like web browser or text editor while support for undo can be implemented with an unbounded stackmany applications provide only limited support for such an undo historywith fixed-capacity stack when push is invoked with the stack at full capacityrather than throwing full exception (as described in exercise - ) more typical semantic is to accept the pushed element at the top while "leakingthe oldest element from the bottom of the stack to make room give an implementation of such leakystack abstractionusing circular array with appropriate storage capacity this class should have public interface similar to the bounded-capacity stack in exercise - but with the desired leaky semantics when full
12,985
- when share of common stock of some company is soldthe capital gain (orsometimeslossis the difference between the share' selling price and the price originally paid to buy it this rule is easy to understand for single sharebut if we sell multiple shares of stock bought over long period of timethen we must identify the shares actually being sold standard accounting principle for identifying which shares of stock were sold in such case is to use fifo protocol--the shares sold are the ones that have been held the longest (indeedthis is the default method built into several personal finance software packagesfor examplesuppose we buy shares at $ each on day shares at $ on day shares at $ on day and then sell shares on day at $ each then applying the fifo protocol means that of the shares sold were bought on day were bought on day and were bought on day the capital gain in this case would therefore be (- )or $ write program that takes as input sequence of transactions of the form "buy share(sat eachor "sell share(sat each,assuming that the transactions occur on consecutive days and the values and are integers given this input sequencethe output should be the total capital gain (or lossfor the entire sequenceusing the fifo protocol to identify shares - design an adt for two-colordouble-stack adt that consists of two stacks--one "redand one "blue"--and has as its operations color-coded versions of the regular stack adt operations for examplethis adt should support both red push operation and blue push operation give an efficient implementation of this adt using single array whose capacity is set at some value that is assumed to always be larger than the sizes of the red and blue stacks combined notes we were introduced to the approach of defining data structures first in terms of their adts and then in terms of concrete implementations by the classic books by ahohopcroftand ullman [ exercises - and - are similar to interview questions said to be from well-known software company for further study of abstract data typessee liskov and guttag [ ]cardelli and wegner [ ]or demurjian [
12,986
linked lists contents singly linked lists implementing stack with singly linked list implementing queue with singly linked list circularly linked lists round-robin schedulers implementing queue with circularly linked list doubly linked lists basic implementation of doubly linked list implementing deque with doubly linked list the positional list adt the positional list abstract data type doubly linked list implementation sorting positional list case studymaintaining access frequencies using sorted list using list with the move-to-front heuristic link-based vs array-based sequences exercises
12,987
in we carefully examined python' array-based list classand in we demonstrated use of that class in implementing the classic stackqueueand dequeue adts python' list class is highly optimizedand often great choice for storage with that saidthere are some notable disadvantages the length of dynamic array might be longer than the actual number of elements that it stores amortized bounds for operations may be unacceptable in real-time systems insertions and deletions at interior positions of an array are expensive in this we introduce data structure known as linked listwhich provides an alternative to an array-based sequence (such as python listboth array-based sequences and linked lists keep elements in certain orderbut using very different style an array provides the more centralized representationwith one large chunk of memory capable of accommodating references to many elements linked listin contrastrelies on more distributed representation in which lightweight objectknown as nodeis allocated for each element each node maintains reference to its element and one or more references to neighboring nodes in order to collectively represent the linear order of the sequence we will demonstrate trade-off of advantages and disadvantages when contrasting array-based sequences and linked lists elements of linked list cannot be efficiently accessed by numeric index kand we cannot tell just by examining node if it is the secondfifthor twentieth node in the list howeverlinked lists avoid the three disadvantages noted above for array-based sequences singly linked lists singly linked listin its simplest formis collection of nodes that collectively form linear sequence each node stores reference to an object that is an element of the sequenceas well as reference to the next node of the list (see figures and msp element next figure example of node instance that forms part of singly linked list the node' element member references an arbitrary object that is an element of the sequence (the airport code mspin this example)while the next member references the subsequent node of the linked list (or none if there is no further node
12,988
lax msp atl head bos tail figure example of singly linked list whose elements are strings indicating airport codes the list instance maintains member named head that identifies the first node of the listand in some applications another member named tail that identifies the last node of the list the none object is denoted as the first and last node of linked list are known as the head and tail of the listrespectively by starting at the headand moving from one node to another by following each node' next referencewe can reach the tail of the list we can identify the tail as the node having none as its next reference this process is commonly known as traversing the linked list because the next reference of node can be viewed as link or pointer to another nodethe process of traversing list is also known as link hopping or pointer hopping linked list' representation in memory relies on the collaboration of many objects each node is represented as unique objectwith that instance storing reference to its element and reference to the next node (or noneanother object represents the linked list as whole minimallythe linked list instance must keep reference to the head of the list without an explicit reference to the headthere would be no way to locate that node (or indirectlyany othersthere is not an absolute need to store direct reference to the tail of the listas it could otherwise be located by starting at the head and traversing the rest of the list howeverstoring an explicit reference to the tail node is common convenience to avoid such traversal in similar regardit is common for the linked list instance to keep count of the total number of nodes that comprise the list (commonly described as the size of the list)to avoid the need to traverse the list to count the nodes for the remainder of this we continue to illustrate nodes as objectsand each node' "nextreference as pointer howeverfor the sake of simplicitywe illustrate node' element embedded directly within the node structureeven though the element isin factan independent object for examplefigure is more compact illustration of the linked list from figure lax head msp atl bos tail figure compact illustration of singly linked listwith elements embedded in the nodes (rather than more accurately drawn as references to external objects
12,989
inserting an element at the head of singly linked list an important property of linked list is that it does not have predetermined fixed sizeit uses space proportionally to its current number of elements when using singly linked listwe can easily insert an element at the head of the listas shown in figure and described with pseudo-code in code fragment the main idea is that we create new nodeset its element to the new elementset its next link to refer to the current headand then set the list' head to point to the new node head msp atl bos (anewest head lax msp atl bos (bnewest lax head msp atl bos (cfigure insertion of an element at the head of singly linked list(abefore the insertion(bafter creation of new node(cafter reassignment of the head reference algorithm add first(le)newest node( {create new node instance storing reference to element enewest next head {set new node' next to reference the old head nodel head newest {set variable head to reference the new nodel size size {increment the node countcode fragment inserting new element at the beginning of singly linked list note that we set the next pointer of the new node before we reassign variable head to it if the list were initially empty ( head is none)then natural consequence is that the new node has its next reference set to none
12,990
inserting an element at the tail of singly linked list we can also easily insert an element at the tail of the listprovided we keep reference to the tail nodeas shown in figure in this casewe create new nodeassign its next reference to noneset the next reference of the tail to point to this new nodeand then update the tail reference itself to this new node we give the details in code fragment tail msp atl bos (atail msp atl newest bos mia (btail msp atl bos newest mia (cfigure insertion at the tail of singly linked list(abefore the insertion(bafter creation of new node(cafter reassignment of the tail reference note that we must set the next link of the tail in (bbefore we assign the tail variable to point to the new node in (calgorithm add last(le)newest node( {create new node instance storing reference to element enewest next none {set new node' next to reference the none objectl tail next newest {make old tail node point to new nodel tail newest {set variable tail to reference the new nodel size size {increment the node countcode fragment inserting new node at the end of singly linked list note that we set the next pointer for the old tail node before we make variable tail point to the new node this code would need to be adjusted for inserting onto an empty listsince there would not be an existing tail node
12,991
removing an element from singly linked list removing an element from the head of singly linked list is essentially the reverse operation of inserting new element at the head this operation is illustrated in figure and given in detail in code fragment head lax msp atl bos (ahead lax msp atl bos (bhead msp atl bos (cfigure removal of an element at the head of singly linked list(abefore the removal(bafter "linking outthe old head(cfinal configuration algorithm remove first( )if head is none then indicate an errorthe list is empty head head next {make head point to next node (or none) size size {decrement the node countcode fragment removing the node at the beginning of singly linked list unfortunatelywe cannot easily delete the last node of singly linked list even if we maintain tail reference directly to the last node of the listwe must be able to access the node before the last node in order to remove the last node but we cannot reach the node before the tail by following next links from the tail the only way to access this node is to start from the head of the list and search all the way through the list but such sequence of link-hopping operations could take long time if we want to support such an operation efficientlywe will need to make our list doubly linked (as we do in section
12,992
implementing stack with singly linked list in this sectionwe demonstrate use of singly linked list by providing complete python implementation of the stack adt (see section in designing such an implementationwe need to decide whether to model the top of the stack at the head or at the tail of the list there is clearly best choice herewe can efficiently insert and delete elements in constant time only at the head since all stack operations affect the topwe orient the top of the stack at the head of our list to represent individual nodes of the listwe develop lightweight node class this class will never be directly exposed to the user of our stack classso we will formally define it as nonpublicnested class of our eventual linkedstack class (see section for discussion of nested classesthe definition of the node class is shown in code fragment class node"""lightweightnonpublic class for storing singly linked node ""slots _element _next streamline memory usage def init (selfelementnext)self element element self next next initialize node' fields reference to user' element reference to next node code fragment lightweight node class for singly linked list node has only two instance variableselement and next we intentionally define slots to streamline the memory usage (see page of section for discussion)because there may potentially be many node instances in single list the constructor of the node class is designed for our convenienceallowing us to specify initial values for both fields of newly created node complete implementation of our linkedstack class is given in code fragments and each stack instance maintains two variables the head member is reference to the node at the head of the list (or noneif the stack is emptywe keep track of the current number of elements with the size instance variablefor otherwise we would be forced to traverse the entire list to count the number of elements when reporting the size of the stack the implementation of push essentially mirrors the pseudo-code for insertion at the head of singly linked list as outlined in code fragment when we push new element onto the stackwe accomplish the necessary changes to the linked structure by invoking the constructor of the node class as followsself head self node(eself headcreate and link new node note that the next field of the new node is set to the existing top nodeand then self head is reassigned to the new node
12,993
linked lists class linkedstack """lifo stack implementation using singly linked list for storage "" nested node class class node """lightweightnonpublic class for storing singly linked node ""slots _element _next streamline memory usage initialize node' fields def init (selfelementnext)reference to user' element self element element reference to next node self next next stack methods def init (self) """create an empty stack ""reference to the head node self head none number of stack elements self size def len (self) """return the number of elements in the stack "" return self size def is empty(self) """return true if the stack is empty "" return self size = def push(selfe) """add element to the top of the stack ""create and link new node self head self node(eself head self size + 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 top of stack is at head of list return self head element code fragment implementation of stack adt using singly linked list (continued in code fragment
12,994
def pop(self)"""remove and return the element from the top of the stack ( liforaise empty exception if the stack is empty ""if self is empty)raise emptystack is empty answer self head element bypass the former top node self head self head next self size - return answer code fragment implementation of stack adt using singly linked list (continued from code fragment when implementing the top methodthe goal is to return the element that is at the top of the stack when the stack is emptywe raise an empty exceptionas originally defined in code fragment of when the stack is nonemptyself head is reference to the first node of the linked list the top element can be identified as self head element our implementation of pop essentially mirrors the pseudo-code given in code fragment except that we maintain local reference to the element that is stored at the node that is being removedand we return that element to the caller of pop the analysis of our linkedstack operations is given in table we see that all of the methods complete in worst-case constant time this is in contrast to the amortized bounds for the arraystack that were given in table operation push(es pops toplen(ss is emptyrunning time ( ( ( ( ( table performance of our linkedstack implementation all bounds are worstcase and our space usage is ( )where is the current number of elements in the stack
12,995
implementing queue with singly linked list as we did for the stack adtwe can use singly linked list to implement the queue adt while supporting worst-case ( )-time for all operations because we need to perform operations on both ends of the queuewe will explicitly maintain both head reference and tail reference as instance variables for each queue the natural orientation for queue is to align the front of the queue with the head of the listand the back of the queue with the tail of the listbecause we must be able to enqueue elements at the backand dequeue them from the front (recall from the introduction of section that we are unable to efficiently remove elements from the tail of singly linked list our implementation of linkedqueue class is given in code fragments and class linkedqueue """fifo queue implementation using singly linked list for storage "" class node """lightweightnonpublic class for storing singly linked node "" (omitted hereidentical to that of linkedstack node def init (self) """create an empty queue "" self head none self tail none number of queue elements self size 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 "" if self is empty) raise emptyqueue is empty front aligned with head of list return self head element code fragment implementation of queue adt using singly linked list (continued in code fragment
12,996
def dequeue(self)"""remove and return the first element of the queue ( fiforaise empty exception if the queue is empty ""if self is empty)raise emptyqueue is empty answer self head element self head self head next self size - special case as queue is empty if self is empty)removed head had been the tail self tail none return answer def enqueue(selfe)"""add an element to the back of queue ""node will be new tail node newest self node(enoneif self is empty)special casepreviously empty self head newest elseself tail next newest update reference to tail node self tail newest self size + code fragment implementation of queue adt using singly linked list (continued from code fragment many aspects of our implementation are similar to that of the linkedstack classsuch as the definition of the nested node class our implementation of dequeue for linkedqueue is similar to that of pop for linkedstackas both remove the head of the linked list howeverthere is subtle difference because our queue must accurately maintain the tail reference (no such variable was maintained for our stackin generalan operation at the head has no effect on the tailbut when dequeue is invoked on queue with one elementwe are simultaneously removing the tail of the list we therefore set self tail to none for consistency there is similar complication in our implementation of enqueue the newest node always becomes the new tail yet distinction is made depending on whether that new node is the only node in the list in that caseit also becomes the new headotherwise the new node must be linked immediately after the existing tail node in terms of performancethe linkedqueue is similar to the linkedstack in that all operations run in worst-case constant timeand the space usage is linear in the current number of elements
12,997
circularly linked lists in section we introduced the notion of "circulararray and demonstrated its use in implementing the queue adt in realitythe notion of circular array was artificialin that there was nothing about the representation of the array itself that was circular in structure it was our use of modular arithmetic when "advancingan index from the last slot to the first slot that provided such an abstraction in the case of linked liststhere is more tangible notion of circularly linked listas we can have the tail of the list use its next reference to point back to the head of the listas shown in figure we call such structure circularly linked list lax msp atl head bos tail figure example of singly linked list with circular structure circularly linked list provides more general model than standard linked list for data sets that are cyclicthat iswhich do not have any particular notion of beginning and end figure provides more symmetric illustration of the same circular list structure as figure lax msp bos current atl figure example of circular linked listwith current denoting reference to select node circular view similar to figure could be usedfor exampleto describe the order of train stops in the chicago loopor the order in which players take turns during game even though circularly linked list has no beginning or endper sewe must maintain reference to particular node in order to make use of the list we use the identifier current to describe such designated node by setting current current nextwe can effectively advance through the nodes of the list
12,998
round-robin schedulers to motivate the use of circularly linked listwe consider round-robin schedulerwhich iterates through collection of elements in circular fashion and "serviceseach element by performing given action on it such scheduler is usedfor exampleto fairly allocate resource that must be shared by collection of clients for instanceround-robin scheduling is often used to allocate slices of cpu time to various applications running concurrently on computer round-robin scheduler could be implemented with the general queue adtby repeatedly performing the following steps on queue (see figure ) dequeue( service element enqueue(ethe queue deque the next element service the next element enqueue the serviced element shared service figure the three iterative steps for round-robin scheduling using queue if we use of the linkedqueue class of section for such an applicationthere is unnecessary effort in the combination of dequeue operation followed soon after by an enqueue of the same element one node is removed from the listwith appropriate adjustments to the head of the list and the size decrementedand then new node is created to reinsert at the tail of the list and the size is incremented if using circularly linked listthe effective transfer of an item from the "headof the list to the "tailof the list can be accomplished by advancing reference that marks the boundary of the queue we will next provide an implementation of circularqueue class that supports the entire queue adttogether with an additional methodrotate)that moves the first element of the queue to the back ( similar method is supported by the deque class of python' collections modulesee table with this operationa round-robin schedule can more efficiently be implemented by repeatedly performing the following steps service element front( rotate(
12,999
linked lists implementing queue with circularly linked list to implement the queue adt using circularly linked listwe rely on the intuition of figure in which the queue has head and tailbut with the next reference of the tail linked to the head given such modelthere is no need for us to explicitly store references to both the head and the tailas long as we keep reference to the tailwe can always find the head by following the tail' next reference code fragments and provide an implementation of circularqueue class based on this model the only two instance variables are tailwhich is reference to the tail node (or none when empty)and sizewhich is the current number of elements in the queue when an operation involves the front of the queuewe recognize self tail next as the head of the queue when enqueue is calleda new node is placed just after the tail but before the current headand then the new node becomes the tail in addition to the traditional queue operationsthe circularqueue class supports rotate method that more efficiently enacts the combination of removing the front element and reinserting it at the back of the queue with the circular representationwe simply set self tail self tail next to make the old head become the new tail (with the node after the old head becoming the new head class circularqueue """queue implementation using circularly linked list for storage "" class node """lightweightnonpublic class for storing singly linked node "" (omitted hereidentical to that of linkedstack node def init (self) """create an empty queue ""will represent tail of queue self tail none number of queue elements self size 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 = code fragment implementation of circularqueue classusing circularly linked list as storage (continued in code fragment