id
int64
0
25.6k
text
stringlengths
0
4.59k
21,800
- consider the following "justificationthat the fibonacci functionf( (see proposition is ( )base case ( < ) ( and ( induction step ( )assume claim true for consider (nf( ( by inductionf( is ( and ( is ( thenf(nis (( ( ))by the identity presented in exercise - thereforef(nis (nwhat is wrong with this "justification" - c...
21,801
- perform experimental analysis to test the hypothesis that python' sorted method runs in ( log ntime on average - for each of the three algorithmsunique unique and unique which solve the element uniqueness problemperform an experimental analysis to determine the largest value of such that the given algorithm runs in o...
21,802
recursion contents illustrative examples the factorial function drawing an english ruler binary search file systems analyzing recursive algorithms recursion run amok maximum recursive depth in python further examples of recursion linear recursion binary recursion multiple recursion designing recursive algorithms elimin...
21,803
one way to describe repetition within computer program is the use of loopssuch as python' while-loop and for-loop constructs described in section an entirely different way to achieve repetition is through process known as recursion recursion is technique by which function makes one or more calls to itself during execut...
21,804
illustrative examples the factorial function to demonstrate the mechanics of recursionwe begin with simple mathematical example of computing the value of the factorial function the factorial of positive integer ndenoted !is defined as the product of the integers from to if then nis defined as by convention more formall...
21,805
this function does not use any explicit loops repetition is provided by the repeated recursive invocations of the function there is no circularity in this definitionbecause each time the function is invokedits argument is smaller by oneand when base case is reachedno further recursive calls are made we illustrate the e...
21,806
drawing an english ruler in the case of computing factorialthere is no compelling reason for preferring recursion over direct iteration with loop as more complex example of the use of recursionconsider how to draw the markings of typical english ruler for each inchwe place tick with numeric label we denote the length o...
21,807
in generalan interval with central tick length > is composed ofan interval with central tick length single tick of length an interval with central tick length although it is possible to draw such ruler using an iterative process (see exercise - )the task is considerably easier to accomplish with recursion our implement...
21,808
illustrating ruler drawing using recursion trace the execution of the recursive draw interval function can be visualized using recursion trace the trace for draw interval is more complicated than in the factorial examplehoweverbecause each instance makes two recursive calls to illustrate thiswe will show the recursion ...
21,809
binary search in this sectionwe describe classic recursive algorithmbinary searchthat is used to efficiently locate target value within sorted sequence of elements this is among the most important of computer algorithmsand it is the reason that we so often store data in sorted order (as in figure figure values stored i...
21,810
this algorithm is known as binary search we give python implementation in code fragment and an illustration of the execution of the algorithm in figure whereas sequential search runs in (ntimethe more efficient binary search runs in (log ntime this is significant improvementgiven that if is one billionlog is only (we d...
21,811
file systems modern operating systems define file-system directories (which are also sometimes called "folders"in recursive way namelya file system consists of top-level directoryand the contents of this directory consists of files and other directorieswhich in turn can contain files and other directoriesand so on the ...
21,812
/user/rt/courses cs cs grades homeworks programs projects hw hw hw pr pr pr grades papers demos buylow sellhigh market figure the same portion of file system given in figure but with additional annotations to describe the amount of disk space that is used within the icon for each file or directory is the amount of spac...
21,813
python' os module to provide python implementation of recursive algorithm for computing disk usagewe rely on python' os modulewhich provides robust tools for interacting with the operating system during the execution of program this is an extensive librarybut we will only need the following four functionsos path getsiz...
21,814
recursion trace to produce different form of recursion tracewe have included an extraneous print statement within our python implementation (line of code fragment the precise format of that output intentionally mirrors output that is produced by classic unix/linux utility named du (for "disk usage"it reports the amount...
21,815
analyzing recursive algorithms in we introduced mathematical techniques for analyzing the efficiency of an algorithmbased upon an estimate of the number of primitive operations that are executed by the algorithm we use notations such as big-oh to summarize the relationship between the number of operations and the input...
21,816
drawing an english ruler in analyzing the english ruler application from section we consider the fundamental question of how many total lines of output are generated by an initial call to draw interval( )where denotes the center length this is reasonable benchmark for the overall efficiency of the algorithm as each lin...
21,817
justificationto prove this claima crucial fact is that with each recursive call the number of candidate entries still to be searched is given by the value high low moreoverthe number of remaining candidates is reduced by at least one half with each recursive call specificallyfrom the definition of midthe number of rema...
21,818
recursion to formalize this argumentwe can define the nesting level of each entry such that the entry on which we begin has nesting level entries stored directly within it have nesting level entries stored within those entries have nesting level and so on we can prove by induction that there is exactly one recursive in...
21,819
recursion run amok although recursion is very powerful toolit can easily be misused in various ways in this sectionwe examine several problems in which poorly implemented recursion causes drastic inefficiencyand we discuss some strategies for recognizing and avoid such pitfalls we begin by revisiting the element unique...
21,820
an inefficient recursion for computing fibonacci numbers in section we introduced process for generating the fibonacci numberswhich can be defined recursively as followsf fn fn- fn- for ironicallya direct implementation based on this definition results in the function bad fibonacci shown in code fragment which computes...
21,821
an efficient recursion for computing fibonacci numbers we were tempted into using the bad recursion formulation because of the way the nth fibonacci numberfn depends on the two previous valuesfn- and fn- but notice that after computing fn- the call to compute fn- requires its own recursive call to compute fn- as it doe...
21,822
maximum recursive depth in python another danger in the misuse of recursion is known as infinite recursion if each recursive call makes another recursive callwithout ever reaching base casethen we have an infinite series of such calls this is fatal error an infinite recursion can quickly swamp computing resourcesnot on...
21,823
further examples of recursion in the remainder of this we provide additional examples of the use of recursion we organize our presentation by considering the maximum number of recursive calls that may be started from within the body of single activation if recursive call starts at most one otherwe call this linear recu...
21,824
recursive algorithm for computing the sum of sequence of numbers based on this intuition is implemented in code fragment def linear sum(sn) """return the sum of the first numbers of sequence "" if = return else return linear sum(sn- [ - code fragment summing the elements of sequence using linear recursion recursion tra...
21,825
reversing sequence with recursion nextlet us consider the problem of reversing the elements of sequencesso that the first element becomes the lastthe second element becomes second to the lastand so on we can solve this problem using linear recursionby observing that the reversal of sequence can be achieved by swapping ...
21,826
recursive algorithms for computing powers as another interesting example of the use of linear recursionwe consider the problem of raising number to an arbitrary nonnegative integern that iswe wish to compute the power functiondefined as power(xnxn (we use the name "powerfor this discussionto differentiate from the buil...
21,827
def power(xn) """compute the value for integer "" if = return else partial power(xn / rely on truncated division result partial partial if = if oddinclude extra factor of result return result code fragment computing the power function using repeated squaring to illustrate the execution of our improved algorithmfigure p...
21,828
binary recursion when function makes two recursive callswe say that it uses binary recursion we have already seen several examples of binary recursionmost notably when drawing the english ruler (section )or in the bad fibonacci function of section as another application of binary recursionlet us revisit the problem of ...
21,829
multiple recursion generalizing from binary recursionwe define multiple recursion as process in which function may make more than two recursive calls our recursion for analyzing the disk space usage of file system (see section is an example of multiple recursionbecause the number of recursive calls made during one invo...
21,830
algorithm puzzlesolve( , , )inputan integer ksequence sand set outputan enumeration of all -length extensions to using elements in without repetitions for each in do add to the end of remove from { is now being usedif = then test whether is configuration that solves the puzzle if solves the puzzle then return "solution...
21,831
designing recursive algorithms in generalan algorithm that uses recursion typically has the following formtest for base cases we begin by testing for set of base cases (there should be at least onethese base cases should be defined so that every possible chain of recursive calls will eventually reach base caseand the h...
21,832
eliminating tail recursion the main benefit of recursive approach to algorithm design is that it allows us to succinctly take advantage of repetitive structure present in many problems by making our algorithm description exploit the repetitive structure in recursive waywe can often avoid complex case analyses and neste...
21,833
def binary search iterative(datatarget) """return true if target is found in the given python list "" low high len(data)- while low <high mid (low high/ if target =data[mid]found match return true elif target data[mid] high mid only consider values left of mid else low mid only consider values right of mid return false...
21,834
exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - describe recursive algorithm for finding the maximum element in sequencesof elements what is your running time and space usager- draw the recursion trace for the computation of power( )using the traditional function imp...
21,835
- in section we prove by induction that the number of lines printed by call to draw interval(cis another interesting question is how many dashes are printed during that process prove by induction that the number of dashes printed by draw interval(cis + - in the towers of hanoi puzzlewe are given platform with three peg...
21,836
- suppose you are given an -element sequencescontaining distinct integers that are listed in increasing order given number kdescribe recursive algorithm to find two integers in that sum to kif such pair exists what is the running time of your algorithmc- develop nonrecursive implementation of the version of power from ...
21,837
array-based sequences contents python' sequence types low-level arrays referential arrays compact arrays in python dynamic arrays and amortization implementing dynamic array amortized analysis of dynamic arrays python' list class efficiency of python' sequence types python' list and tuple classes python' string class u...
21,838
python' sequence types in this we explore python' various "sequenceclassesnamely the builtin listtupleand str classes there is significant commonality between these classesmost notablyeach supports indexing to access an individual element of sequenceusing syntax such as seq[ ]and each uses low-level concept known as an...
21,839
low-level arrays to accurately describe the way in which python represents the sequence typeswe must first discuss aspects of the low-level computer architecture the primary memory of computer is composed of bits of informationand those bits are typically grouped into larger units that depend upon the precise system ar...
21,840
group of related variables can be stored one after another in contiguous portion of the computer' memory we will denote such representation as an array as tangible examplea text string is stored as an ordered sequence of individual characters in pythoneach character is represented using the unicode character setand on ...
21,841
referential arrays as another motivating exampleassume that we want medical information system to keep track of the patients currently assigned to beds in certain hospital if we assume that the hospital has bedsand conveniently that those beds are numbered from to we might consider using an array-based structure to mai...
21,842
the fact that lists and tuples are referential structures is significant to the semantics of these classes single list instance may include multiple references to the same object as elements of the listand it is possible for single object to be an element of two or more listsas those lists simply store references back ...
21,843
as more striking exampleit is common practice in python to initialize an array of integers using syntax such as counters [ this syntax produces list of length eightwith all eight elements being the value zero technicallyall eight cells of the list reference the same objectas portrayed in figure counters figure the resu...
21,844
compact arrays in python in the introduction to this sectionwe emphasized that strings are represented using an array of characters (not an array of referenceswe will refer to this more direct representation as compact array because the array is storing the bits that represent the primary data (charactersin the case of...
21,845
primary support for compact arrays is in module named array that module defines classalso named arrayproviding compact storage for arrays of primitive data types portrayal of such an array of integers is shown in figure figure integers stored compactly as elements of python array the public interface for the array clas...
21,846
dynamic arrays and amortization when creating low-level array in computer systemthe precise size of that array must be explicitly declared in order for the system to properly allocate consecutive piece of memory for its storage for examplefigure displays an array of bytes that might be stored in memory locations throug...
21,847
import sys provides getsizeof function data for in range( )notemust fix choice of len(datanumber of elements sys getsizeof(dataactual size in bytes printlength{ : }size in bytes{ : dformat(ab) data append(noneincrease length by one code fragment an experiment to explore the relationship between list' length and its und...
21,848
in evaluating the results of the experimentwe draw attention to the first line of output from code fragment we see that an empty list instance already requires certain number of bytes of memory ( on our systemin facteach object in python maintains some statefor examplea reference to denote the class to which it belongs...
21,849
implementing dynamic array although the python list class provides highly optimized implementation of dynamic arraysupon which we rely for the remainder of this bookit is instructive to see how such class might be implemented the key is to provide means to grow the array that stores the elements of list of coursewe can...
21,850
import ctypes provides low-level arrays class dynamicarray """ dynamic array class akin to simplified python list "" def init (self) """create an empty array ""count actual elements self default array capacity self capacity low-level array self self make array(self capacity def len (self) """return number of elements s...
21,851
amortized analysis of dynamic arrays primitive operations for an append in this sectionwe perform detailed analysis of the running time of operations on dynamic arrays we use the big-omega notation introduced in section to give an asymptotic lower bound on the running time of an algorithm or step within it the strategy...
21,852
proposition let be sequence implemented by means of dynamic array with initial capacity oneusing the strategy of doubling the array size when full the total time to perform series of append operations in sstarting from being emptyis (njustificationlet us assume that one cyber-dollar is enough to pay for the execution o...
21,853
geometric increase in capacity although the proof of proposition relies on the array being doubled each time we expandthe ( amortized bound per operation can be proven for any geometrically increasing progression of array sizes (see section for discussion of geometric progressionswhen choosing the geometric basethere e...
21,854
array-based sequences using fixed increment for each resizeand thus an arithmetic progression of intermediate array sizesresults in an overall time that is quadratic in the number of operationsas shown in the following proposition intuitivelyeven an increase in cells per resize will become insignificant for large data ...
21,855
python' list class the experiments of code fragment and at the beginning of section provide empirical evidence that python' list class is using form of dynamic arrays for its storage yeta careful examination of the intermediate array capacities (see exercises - and - suggests that python is not using pure geometric pro...
21,856
efficiency of python' sequence types in the previous sectionwe began to explore the underpinnings of python' list classin terms of implementation strategies and efficiency we continue in this section by examining the performance of all of python' sequence types python' list and tuple classes the nonmutating behaviors o...
21,857
searching for occurrences of value each of the countindexand contains methods proceed through iteration of the sequence from left to right in factcode fragment of section demonstrates how those behaviors might be implemented notablythe loop for computing the count must proceed through the entire sequencewhile the loops...
21,858
operation data[jval data append(valuedata insert(kvaluedata popdata pop(kdel data[kdata remove(valuedata extend(data data +data data reversedata sortrunning time ( ( ) ( ) ( ) ( ) ( ) ( ) (no( log namortized table asymptotic performance of the mutating behaviors of the list class identifiers datadata and data designate...
21,859
- figure creating room to insert new element at index of dynamic array that process depends upon the index of the new elementand thus the number of other elements that must be shifted that loop copies the reference that had been at index to index nthen the reference that had been at index to continuing until copying th...
21,860
removing elements from list python' list class offers several ways to remove an element from list call to popremoves the last element from list this is most efficientbecause all other elements remain in their original location this is effectively an ( operationbut the bound is amortized because python will occasionally...
21,861
extending list python provides method named extend that is used to add all elements of one list to the end of second list in effecta call to data extend(otherproduces the same outcome as the codefor element in otherdata append(elementin either casethe running time is proportional to the length of the other listand amor...
21,862
python' string class strings are very important in python we introduced their use in with discussion of various operator syntaxes in section comprehensive summary of the named methods of the class is given in tables through of appendix we will not formally analyze the efficiency of each of those behaviors in this secti...
21,863
while the preceding code fragment accomplishes the goalit may be terribly inefficient because strings are immutablethe commandletters +cwould presumably compute the concatenationletters cas new string instance and then reassign the identifierlettersto that result constructing that new string would require time proporti...
21,864
using array-based sequences storing high scores for game the first application we study is storing sequence of high score entries for video game this is representative of many applications in which sequence of objects must be stored we could just as easily have chosen to store records for patients in hospital or the na...
21,865
class for high scores to maintain sequence of high scoreswe develop class named scoreboard scoreboard is limited to certain number of high scores that can be savedonce that limit is reacheda new score only qualifies for the scoreboard if it is strictly higher than the lowest "high scoreon the board the length of the de...
21,866
array-based sequences class scoreboard """fixed-length sequence of high scores in nondecreasing order "" def init (selfcapacity= ) """initialize scoreboard with given maximum capacity all entries are initially none ""reserve space for future scores self board [nonecapacity number of actual entries self def getitem (sel...
21,867
adding an entry the most interesting method of the scoreboard class is addwhich is responsible for considering the addition of new entry to the scoreboard keep in mind that every entry will not necessarily qualify as high score if the board is not yet fullany new entry will be retained once the board is fulla new entry...
21,868
sorting sequence in the previous subsectionwe considered an application for which we added an object to sequence at given position while shifting other elements so as to keep the previous order intact in this sectionwe use similar technique to solve the sorting problemthat isstarting with an unordered sequence of eleme...
21,869
def insertion sort( ) """sort list of comparable elements into nondecreasing order "" for in range( len( ))from to - cur [kcurrent element to be inserted = find correct index for current while and [ - curelement [ - must be after current [ja[ - - [jcur cur is now in the right place code fragment python code for perform...
21,870
simple cryptography an interesting application of strings and lists is cryptographythe science of secret messages and their applications this field studies ways of performing encryptionwhich takes messagecalled the plaintextand converts it into scrambled messagecalled the ciphertext likewisecryptography also studies co...
21,871
we can represent replacement rule using another string to describe the translation as concrete examplesuppose we are using caesar cipher with threecharacter rotation we can precompute string that represents the replacements that should be used for each character from to for examplea should be replaced by db replaced by...
21,872
array-based sequences class caesarcipher """class for doing encryption and decryption using caesar cipher "" def init (selfshift) """construct caesar cipher using given integer shift for rotation ""temp array for encryption encoder [none temp array for decryption decoder [none for in range( ) encoder[kchr(( shift orda ...
21,873
multidimensional data sets liststuplesand strings in python are one-dimensional we use single index to access each element of the sequence many computer applications involve multidimensional data sets for examplecomputer graphics are often modeled in either two or three dimensions geographic information may be naturall...
21,874
constructing multidimensional list to quickly initialize one-dimensional listwe generally rely on syntax such as data [ to create list of zeros on page we emphasized that from technical perspectivethis creates list of length with all entries referencing the same integer instancebut that there was no meaningful conseque...
21,875
data figure valid representation of data set as list of lists (for simplicitywe overlook the fact that the values in the secondary lists are referential to properly initialize two-dimensional listwe must ensure that each cell of the primary list refers to an independent instance of secondary list this can be accomplish...
21,876
our representation of board will be list of lists of characterswith or designating player' moveor designating an empty space for examplethe board configuration will be stored internally as ] ] ]we develop complete python class for maintaining tic-tac-toe board for two players that class will keep track of the moves and...
21,877
class tictactoe """management of tic-tac-toe game (does not do strategy"" def init (self) """start new game "" self board for in range( self player def mark(selfij) """put an or mark at position ( ,jfor next player turn "" if not ( < < and < < ) raise valueerrorinvalid board position if self board[ ][ ! raise valueerro...
21,878
exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - execute the experiment from code fragment and compare the results on your system to those we report in code fragment - in code fragment we perform an experiment to compare the length of python list to its underlying mem...
21,879
- explain the changes that would have to be made to the program of code fragment so that it could perform the caesar cipher for messages that are written in an alphabet-based language other than englishsuch as greekrussianor hebrew - the constructor for the caesarcipher class in code fragment can be implemented with tw...
21,880
array-based sequences - give formal proof that any sequence of append or pop operations on an initially empty dynamic array takes (ntimeif using the strategy described in exercise - - consider variant of exercise - in which an array of capacity is resized to capacity precisely that of the number of elementsany time the...
21,881
- useful operation in databases is the natural join if we view database as list of ordered pairs of objectsthen the natural join of databases and is the list of all ordered triples (xyzsuch that the pair (xyis in and the pair (yzis in describe and analyze an efficient algorithm for computing the natural join of list of...
21,882
stacksqueuesand deques contents stacks the stack abstract data type simple array-based stack implementation reversing data using stack matching parentheses and html tags queues the queue abstract data type array-based queue implementation double-ended queues the deque abstract data type implementing deque with circular...
21,883
stacks stack is collection of objects that are inserted and removed according to the last-infirst-out (lifoprinciple user may insert objects into stack at any timebut may only access or remove the most recently inserted object that remains (at the so-called "topof the stackthe name "stackis derived from the metaphor of...
21,884
the stack abstract data type stacks are the simplest of all data structuresyet they are also among the most important they are used in host of different applicationsand as tool for many more sophisticated data structures and algorithms formallya stack is an abstract data type (adtsuch that an instance supports the foll...
21,885
simple array-based stack implementation we can implement stack quite easily by storing its elements in python list the list class already supports adding an element to the end with the append methodand removing the last element with the pop methodso it is natural to align the top of the stack at the end of the listas s...
21,886
implementing stack using python list we use the adapter design pattern to define an arraystack class that uses an underlying python list for storage (we choose the name arraystack to emphasize that the underlying storage is inherently array based one question that remains is what our code should do if user calls pop or...
21,887
class arraystack """lifo stack implementation using python list as underlying storage "" def init (self) """create an empty stack ""nonpublic list instance self data def len (self) """return the number of elements in the stack "" return len(self data def is empty(self) """return true if the stack is empty "" return len...
21,888
analyzing the array-based stack implementation table shows the running times for our arraystack methods the analysis directly mirrors the analysis of the list class given in section the implementations for topis emptyand len use constant time in the worst case the ( time for push and pop are amortized bounds (see secti...
21,889
reversing data using stack as consequence of the lifo protocola stack can be used as general tool to reverse data sequence for exampleif the values and are pushed onto stack in that orderthey will be popped from the stack in the order and then this idea can be applied in variety of settings for examplewe might wish to ...
21,890
matching parentheses and html tags in this subsectionwe explore two related applications of stacksboth of which involve testing for pairs of matching delimiters in our first applicationwe consider arithmetic expressions that may contain various pairs of grouping symbolssuch as parentheses"(and ")braces"{and "}brackets"...
21,891
we assume the input is sequence of characterssuch as [( + )-( + )we perform left-to-right scan of the original sequenceusing stack to facilitate the matching of grouping symbols each time we encounter an opening symbolwe push that symbol onto sand each time we encounter closing symbolwe pop symbol from the stack (assum...
21,892
in an html documentportions of text are delimited by html tags simple opening html tag has the form "and the corresponding closing tag has the form "for examplewe see the tag on the first line of figure ( )and the matching tag at the close of that document other commonly used html tags that are used in this example inc...
21,893
queues another fundamental data structure is the queue it is close "cousinof the stackas queue is collection of objects that are inserted and removed according to the first-infirst-out (fifoprinciple that iselements can be inserted at any timebut only the element that has been in the queue the longest can be next remov...
21,894
the queue abstract data type formallythe queue abstract data type defines collection that keeps objects in sequencewhere element access and deletion are restricted to the first element in the queueand element insertion is restricted to the back of the sequence this restriction enforces the rule that items are inserted ...
21,895
array-based queue implementation for the stack adtwe created very simple adapter class that used python list as the underlying storage it may be very tempting to use similar approach for supporting the queue adt we could enqueue element by calling append(eto add it to the end of the list we could use the syntax pop( )a...
21,896
using an array circularly in developing more robust queue implementationwe allow the front of the queue to drift rightwardand we allow the contents of the queue to "wrap aroundthe end of an underlying array we assume that our underlying array has fixed length that is greater that the actual number of elements in the qu...
21,897
class arrayqueue """fifo queue implementation using python list as underlying storage ""moderate capacity for all new queues default capacity def init (self) """create an empty queue "" self data [nonearrayqueue default capacity self size self front def len (self) """return the number of elements in the queue "" return...
21,898
def enqueue(selfe)"""add an element to the back of queue ""if self size =len(self data)double the array size self resize( len(self data)avail (self front self sizelen(self dataself data[availe self size + we assume cap >len(selfdef resize(selfcap)"""resize to new list of capacity >len(self""keep track of existing list ...
21,899
when the dequeue method is calledthe current value of self front designates the index of the value that is to be removed and returned we keep local reference to the element that will be returnedsetting answer self data[self frontjust prior to removing the reference to that object from the listwith the assignment self d...