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 recu...
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 tra...
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 ...
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 buil...
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 p...
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 ...
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 invo...
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...
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 h...
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 neste...
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...
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 imp...
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 peg...
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 ...
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 u...
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...
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 ar...
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 ...
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 mai...
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 ...
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 resu...
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...
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 clas...
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 throug...
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 und...
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...
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 can...
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 s...
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...
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 o...
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 e...
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 ...
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 pro...
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 o...
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...
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...
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 th...
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...
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 amor...
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 secti...
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 proporti...
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 na...
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 de...
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 (sel...
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...
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 eleme...
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 perform...
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 co...
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...
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 ...
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 naturall...
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 conseque...
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 accomplish...
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...
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 valueerro...
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 mem...
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 tw...
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...
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...
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...
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...
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 foll...
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 s...
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...
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...
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 secti...
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 ...
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"...
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 (assum...
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 inc...
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 remov...
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 ...
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( )a...
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 qu...
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...
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 ...
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 d...
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 a...
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 t...
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 wit...
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 fir...
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( - s...
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( )dele...
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 ...
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...
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...
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 link...
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 t...
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 denot...
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...
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 ...
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 (cfigu...
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 ...
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 e...
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 si...
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 inst...
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 ...
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 arithm...
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...
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 b...