id
int64
0
25.6k
text
stringlengths
0
4.59k
13,000
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 head self tail next return head element def dequeue(self)"""remove and return the first element of the queue ( fiforaise empty exception if the queue ...
13,001
doubly linked lists in singly linked listeach node maintains reference to the node that is immediately after it we have demonstrated the usefulness of such representation when managing sequence of elements howeverthere are limitations that stem from the asymmetry of singly linked list in the opening of section we empha...
13,002
advantage of using sentinels although we could implement doubly linked list without sentinel nodes (as we did with our singly linked list in section )the slight extra space devoted to the sentinels greatly simplifies the logic of our operations most notablythe header and trailer nodes never change--only the nodes betwe...
13,003
header trailer bwi jfk sfo (aheader trailer pvd bwi jfk sfo (bheader trailer pvd bwi jfk sfo (cfigure adding an element to the front of sequence represented by doubly linked list with header and trailer sentinels(abefore the operation(bafter creating the new node(cafter linking the neighbors to the new node the deletio...
13,004
basic implementation of doubly linked list we begin by providing preliminary implementation of doubly linked listin the form of class named doublylinkedbase we intentionally name the class with leading underscore because we do not intend for it to provide coherent public interface for general use we will see that linke...
13,005
linked lists class doublylinkedbase """ base class providing doubly linked list representation "" class node """lightweightnonpublic class for storing doubly linked node "" (omitted heresee previous code fragment def init (self) """create an empty list "" self header self node(nonenonenone self trailer self node(noneno...
13,006
the other two methods of our class are the nonpublic utilitiesinsert between and delete node these provide generic support for insertions and deletionsrespectivelybut require one or more node references as parameters the implementation of the insert between method is modeled upon the algorithm that was previously portr...
13,007
class linkeddequedoublylinkedbase)note the use of inheritance """double-ended queue implementation based on doubly linked list "" def first(self) """return (but do not removethe element at the front of the deque "" if self is empty) raise empty("deque is empty"real item just after header return self header next element...
13,008
the positional list adt the abstract data types that we have considered thus farnamely stacksqueuesand double-ended queuesonly allow update operations that occur at one end of sequence or the other we wish to have more general abstraction for examplealthough we motivated the fifo semantics of queue as model for custome...
13,009
as another examplea text document can be viewed as long sequence of characters word processor uses the abstraction of cursor to describe position within the document without explicit use of an integer indexallowing operations such as "delete the character at the cursoror "insert new character just after the cursor furt...
13,010
the positional list abstract data type to provide for general abstraction of sequence of elements with the ability to identify the location of an elementwe define positional list adt as well as simpler position abstract data type to describe location within list position acts as marker or token within the broader posit...
13,011
note well that the firstand lastmethods of the positional list adt return the associated positionsnot the elements (this is in contrast to the corresponding first and last methods of the deque adt the first element of positional list can be determined by subsequently invoking the element method on that positionas first...
13,012
doubly linked list implementation in this sectionwe present complete implementation of positionallist class using doubly linked list that satisfies the following important proposition proposition each method of the positional list adt runs in worst-case ( time when implemented with doubly linked list we rely on the dou...
13,013
linked lists class positionallistdoublylinkedbase) """ sequential container of elements allowing positional access "" nested position class class position """an abstraction representing the location of single element "" def init (selfcontainernode) """constructor should not be invoked by user "" self container containe...
13,014
utility method def make position(selfnode)"""return position instance for given node (or none if sentinel""if node is self header or node is self trailerreturn none boundary violation elsereturn self position(selfnodelegitimate position accessors def first(self)"""return the first position in the list (or none if list ...
13,015
mutators override inherited version to return positionrather than node def insert between(selfepredecessorsuccessor)"""add element between existing nodes and return new position ""node superinsert between(epredecessorsuccessorreturn self make position(nodedef add first(selfe)"""insert element at the front of the list a...
13,016
sorting positional list in section we introduced the insertion-sort algorithmin the context of an array-based sequence in this sectionwe develop an implementation that operates on positionallistrelying on the same high-level algorithm in which each element is placed relative to growing collection of previously sorted e...
13,017
case studymaintaining access frequencies the positional list adt is useful in number of settings for examplea program that simulates game of cards could model each person' hand as positional list (exercise - since most people keep cards of the same suit togetherinserting and removing cards from person' hand could be im...
13,018
using the composition pattern we wish to implement favorites list by making use of positionallist for storage if elements of the positional list were simply elements of the favorites listwe would be challenged to maintain access counts and to keep the proper count with the associated element as the contents of the list...
13,019
public methods def init (self)"""create an empty list of favorites ""will be list of item instances self data positionallistdef len (self)"""return number of entries on favorites list ""return len(self datadef is empty(self)"""return true if list is empty ""return len(self data= def access(selfe)"""access element ether...
13,020
using list with the move-to-front heuristic the previous implementation of favorites list performs the access(emethod in time proportional to the index of in the favorites list that isif is the kth most popular element in the favorites listthen accessing it takes (ktime in many real-life access sequences ( web pages vi...
13,021
linked lists the trade-offs with the move-to-front heuristic if we no longer maintain the elements of the favorites list ordered by their access countswhen we are asked to find the most accessed elementswe need to search for them we will implement the top(kmethod as follows we copy all entries of our favorites list int...
13,022
class favoriteslistmtf(favoriteslist) """list of elements ordered with move-to-front heuristic "" we override move up to provide move-to-front semantics def move up(selfp) """move accessed item at position to front of list "" if !self data first)delete/reinsert self data add first(self data delete( ) we override top be...
13,023
link-based vs array-based sequences we close this by reflecting on the relative pros and cons of array-based and link-based data structures that have been introduced thus far the dichotomy between these approaches presents common design decision when choosing an appropriate implementation of data structure there is not...
13,024
advantages of link-based sequences link-based structures provide worst-case time bounds for their operations this is in contrast to the amortized bounds associated with the expansion or contraction of dynamic array (see section when many individual operations are part of larger computationand we only care about the tot...
13,025
exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - give an algorithm for finding the second-to-last node in singly linked list in which the last node is indicated by next reference of none - describe good algorithm for concatenating two singly linked lists and mgiven on...
13,026
- implement functionwith calling syntax max( )that returns the maximum element from positionallist instance containing comparable elements - redo the previously problem with max as method of the positionallist classso that calling syntax maxis supported - update the positionallist class to support an additional method ...
13,027
creativity - give complete implementation of the stack adt using singly linked list that includes header sentinel - give complete implementation of the queue adt using singly linked list that includes header sentinel - implement methodconcatenate( for the linkedqueue class that takes all elements of linkedqueue and app...
13,028
- there is simplebut inefficientalgorithmcalled bubble-sortfor sorting list of comparable elements this algorithm scans the list - timeswherein each scanthe algorithm compares the current element with the next one and swaps them if they are out of order implement bubble sort function that takes positional list as param...
13,029
- an array is sparse if most of its entries are empty ( nonea list can be used to implement such an array efficiently in particularfor each nonempty cell [ ]we can store an entry (iein lwhere is the element stored at [ithis approach allows us to represent using (mstoragewhere is the number of nonempty entries in provid...
13,030
trees contents general trees tree definitions and properties the tree abstract data type computing depth and height binary trees the binary tree abstract data type properties of binary trees implementing trees linked structure for binary trees array-based representation of binary tree linked structure for general trees...
13,031
general trees shuah ishbak midian medan ephah epher hanoch abida eldaah jokshan sheba dedan jacob (israelreuben simeon levi judah dan naphtali gad asher issachar zebulun dinah joseph benjamin zimran esau eliphaz reuel jeush jalam korah ishmael isaac abraham productivity experts say that breakthroughs come by thinking "...
13,032
tree definitions and properties tree is an abstract data type that stores elements hierarchically with the exception of the top elementeach element in tree has parent element and zero or more children elements tree is usually visualized by placing elements inside ovals or rectanglesand by drawing the connections betwee...
13,033
other node relationships two nodes that are children of the same parent are siblings node is external if has no children node is internal if it has one or more children external nodes are also known as leaves example in section we discussed the hierarchical relationship between files and directories in computer' file s...
13,034
example the inheritance relation between classes in python program forms tree when single inheritance is used for examplein section we provided summary of the hierarchy for python' exception typesas portrayed in figure (originally figure the baseexception class is the root of that hierarchywhile all user-defined except...
13,035
ordered trees tree is ordered if there is meaningful linear order among the children of each nodethat iswe purposefully identify the children of node as being the firstsecondthirdand so on such an order is usually visualized by arranging siblings left to rightaccording to their order example the components of structure...
13,036
the tree abstract data type as we did with positional lists in section we define tree adt using the concept of position as an abstraction for node of tree an element is stored at each positionand positions satisfy parent-child relationships that define the tree structure position object for tree supports the methodp el...
13,037
tree abstract base class in python in discussing the object-oriented design principle of abstraction in section we noted that public interface for an abstract data type is often managed in python via duck typing for examplewe defined the notion of the public interface for queue adt in section and have since presented s...
13,038
class tree """abstract base class representing tree structure "" nested position class class position """an abstraction representing the location of single element "" def element(self) """return the element stored at this position "" raise notimplementederrormust be implemented by subclass def eq (selfother) """return ...
13,039
concrete methods implemented in this class def is root(selfp)"""return true if position represents the root of the tree ""return self root= def is leaf(selfp)"""return true if position does not have any children ""return self num children( = def is empty(self)"""return true if the tree is empty ""return len(self= code ...
13,040
height the height of position in tree is also defined recursivelyif is leafthen the height of is otherwisethe height of is one more than the maximum of the heights of ' children the height of nonempty tree is the height of the root of for examplethe tree of figure has height in additionheight can also be viewed as foll...
13,041
it is important to understand why algorithm height is more efficient than height the algorithm is recursiveand it progresses in top-down fashion if the method is initially called on the root of it will eventually be called once for each position of this is because the root eventually invokes the recursion on each of it...
13,042
binary trees binary tree is an ordered tree with the following properties every node has at most two children each child node is labeled as being either left child or right child left child precedes right child in the order of children of node the subtree rooted at left or right child of an internal node is called left...
13,043
example an arithmetic expression can be represented by binary tree whose leaves are associated with variables or constantsand whose internal nodes are associated with one of the operators +-xand (see figure each node in such tree has value associated with it if node is leafthen its value is that of its variable or cons...
13,044
the binary tree abstract data type as an abstract data typea binary tree is specialization of tree that supports three additional accessor methodst left( )return the position that represents the left child of por none if has no left child right( )return the position that represents the right child of por none if has no...
13,045
trees class binarytree(tree) """abstract base class representing binary tree structure "" additional abstract methods def left(selfp) """return position representing left child return none if does not have left child "" raise notimplementederrormust be implemented by subclass def right(selfp) """return position represe...
13,046
properties of binary trees binary trees have several interesting properties dealing with relationships between their heights and number of nodes we denote the set of all nodes of tree at the same depth as level of in binary treelevel has at most one node (the root)level has at most two nodes (the children of the root)l...
13,047
relating internal nodes to external nodes in proper binary tree in addition to the earlier binary tree propertiesthe following relationship exists between the number of internal nodes and external nodes in proper binary tree proposition in nonempty proper binary tree with ne external nodes and ni internal nodeswe have ...
13,048
implementing trees the tree and binarytree classes that we have defined thus far in this are both formally abstract base classes although they provide great deal of supportneither of them can be directly instantiated we have not yet defined key implementation details for how tree will be represented internallyand how w...
13,049
python implementation of linked binary tree structure in this sectionwe define concrete linkedbinarytree class that implements the binary tree adt by subclassing the binarytree class our general approach is very similar to what we used when developing the positionallist in section we define simplenonpublic node class t...
13,050
for linked binary treesa reasonable set of update methods to support for general usage are the followingt add root( )create root for an empty treestoring as the elementand return the position of that rootan error occurs if the tree is not empty add left(pe)create new node storing element elink the node as the left chil...
13,051
trees class linkedbinarytree(binarytree) """linked representation of binary tree structure "" lightweightnonpublic class for storing node class nodeslots _element _parent _left _right def init (selfelementparent=noneleft=noneright=none) self element element self parent parent self left left self right right class posit...
13,052
binary tree constructor def init (self)"""create an initially empty binary tree ""self root none self size public accessors def len (self)"""return the total number of elements in the tree ""return self size def root(self)"""return the root position of the tree (or none if tree is empty""return self make position(self ...
13,053
def add root(selfe)"""place element at the root of an empty tree and return new position raise valueerror if tree nonempty ""if self root is not noneraise valueerrorroot exists self size self root self node(ereturn self make position(self rootdef add left(selfpe)"""create new left child for position pstoring element re...
13,054
def delete(selfp)"""delete the node at position pand replace it with its childif any return the element that had been stored at position raise valueerror if position is invalid or has two children ""node self validate(pif self num children( = raise valueerrorp has two children might be none child node left if node left...
13,055
performance of the linked binary tree implementation to summarize the efficiencies of the linked structure representationwe analyze the running times of the linkedbinarytree methodsincluding derived methods that are inherited from the tree and binarytree classesthe len methodimplemented in linkedbinarytreeuses an insta...
13,056
array-based representation of binary tree an alternative representation of binary tree is based on way of numbering the positions of for every position of let (pbe the integer defined as follows if is the root of then ( if is the left child of position qthen ( ( if is the right child of position qthen ( ( the numbering...
13,057
the level numbering function suggests representation of binary tree by means of an array-based structure (such as python list)with the element at position of stored at index (pof the array we show an example of an array-based representation of binary tree in figure figure representation of binary tree by means of an ar...
13,058
linked structure for general trees when representing binary tree with linked structureeach node explicitly maintains fields left and right as references to individual children for general treethere is no priori limit on the number of children that node may have natural way to realize general tree as linked structure is...
13,059
tree traversal algorithms traversal of tree is systematic way of accessingor "visiting,all the positions of the specific action associated with the "visitof position depends on the application of this traversaland could involve anything from incrementing counter to performing some complex computation for in this sectio...
13,060
postorder traversal another important tree traversal algorithm is the postorder traversal in some sensethis algorithm can be viewed as the opposite of the preorder traversalbecause it recursively traverses the subtrees rooted at the children of the root firstand then visits the root (hencethe name "postorder"pseudo-cod...
13,061
breadth-first tree traversal although the preorder and postorder traversals are common ways of visiting the positions of treeanother common approach is to traverse tree so that we visit all the positions at depth before we visit the positions at depth such an algorithm is known as breadth-first traversal breadth-first ...
13,062
inorder traversal of binary tree the standard preorderpostorderand breadth-first traversals that were introduced for general treescan be directly applied to binary trees in this sectionwe introduce another common traversal algorithm specifically for binary tree during an inorder traversalwe visit position between the r...
13,063
binary search trees an important application of the inorder traversal algorithm arises when we store an ordered sequence of elements in binary treedefining structure we call binary search tree let be set whose unique elements have an order relation for examples could be set of integers binary search tree for is binary ...
13,064
implementing tree traversals in python when first defining the tree adt in section we stated that tree should include support for the following methodst positions)generate an iteration of all positions of tree iter( )generate an iteration of all elements stored within tree at that timewe did not make any assumption abo...
13,065
def preorder(self)"""generate preorder iteration of positions in the tree ""if not self is empty)for in self subtree preorder(self root))start recursion yield def subtree preorder(selfp)"""generate preorder iteration of positions in subtree rooted at ""yield visit before its subtrees for in self children( )for each chi...
13,066
postorder traversal we can implement postorder traversal using very similar technique as with preorder traversal the only difference is that within the recursive utility for postorder we wait to yield position until after we have recursively yield the positions in its subtrees an implementation is given in code fragmen...
13,067
def breadthfirst(self)"""generate breadth-first iteration of the positions of the tree ""if not self is empty)fringe linkedqueueknown positions not yet yielded fringe enqueue(self root)starting with the root while not fringe is empty) fringe dequeueremove from front of the queue yield report this position for in self c...
13,068
applications of tree traversals in this sectionwe demonstrate several representative applications of tree traversalsincluding some customizations of the standard traversal algorithms table of contents when using tree to represent the hierarchical structure of documenta preorder traversal of the tree can naturally be us...
13,069
preferred approach to producing an indented table of contents is to redesign top-down recursion that includes the current depth as an additional parameter such an implementation is provided in code fragment this implementation runs in worst-case (ntime (excepttechnicallythe time it takes to print strings of increasing ...
13,070
def preorder label(tpdpath) """print labeled representation of subtree of rooted at at depth "" label join(str( + for in pathdisplayed labels are one-indexed labelp element) print( path append( path entries are zero-indexed for in children( )child depth is + preorder label(tcd+ path path[- + path popcode fragment effic...
13,071
def parenthesize(tp) """print parenthesized representation of subtree of rooted at ""use of end avoids trailing newline print( element)end if not is leaf( ) first time true for in children( )determine proper separator sep if first time else print(sependany future passes will not be the first first time false parenthesi...
13,072
euler tours and the template method pattern the various applications described in section demonstrate the great power of recursive tree traversals unfortunatelythey also show that the specific implementations of the preorder and postorder methods of our tree classor the inorder method of the binarytree classare not gen...
13,073
the process of an euler tour can easily be viewed recursively in between the "pre visitand "post visitof given position will be recursive tour of each of its subtrees looking at figure as an examplethere is contiguous portion of the entire tour that is itself an euler tour of the subtree of the node with element "/that...
13,074
class eulertour """abstract base class for performing euler tour of tree hook previsit and hook postvisit may be overridden by subclasses "" def init (selftree) """prepare an euler tour template for given tree "" self tree tree def tree(self) """return reference to the tree being traversed "" return self tree def execu...
13,075
based on our experience of customizing traversals for sample applications section we build support into the primary eulertour for maintaining the recursive depth and the representation of the recursive path through treeusing the approach that we introduced in code fragment we also provide mechanism for one recursive le...
13,076
labeled version of an indentedpreorder presentationakin to code fragment could be generated by the new subclass of eulertour shown in code fragment class preorderprintindentedlabeledtour(eulertour) def hook previsit(selfpdpath) label join(str( + for in pathlabels are one-indexed labelp element) print( code fragment sub...
13,077
the euler tour traversal of binary tree in section we introduced the concept of an euler tour traversal of general graphusing the template method pattern in designing the eulertour class that class provided methods hook previsit and hook postvisit that could be overridden to customize tour in code fragment we provide b...
13,078
figure an inorder drawing of binary tree to demonstrate use of the binaryeulertour frameworkwe develop subclass that computes graphical layout of binary treeas shown in figure the geometry is determined by an algorithm that assigns xand -coordinates to each position of binary tree using the following two rulesx(pis the...
13,079
case studyan expression tree in example we introduced the use of binary tree to represent the structure of an arithmetic expression in this sectionwe define new expressiontree class that provides support for constructing such treesand for displaying and evaluating the arithmetic expression that such tree represents our...
13,080
class expressiontree(linkedbinarytree) """an arithmetic expression tree "" def init (selftokenleft=noneright=none) """create an expression tree in single parameter formtoken should be leaf value ( ) and the expression tree will have that value at an isolated node in three-parameter versiontoken should be an operator an...
13,081
expression tree evaluation the numeric evaluation of an expression tree can be accomplished with simple application of postorder traversal if we know the values represented by the two subtrees of an internal positionwe can calculate the result of the computation that position designates pseudo-code for the recursive ev...
13,082
building an expression tree the constructor for the expressiontree classfrom code fragment provides basic functionality for combining existing trees to build larger expression trees howeverthe question still remains how to construct tree that represents an expression for given stringsuch as ((( + ) )/(( - )+ )to automa...
13,083
exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - the following questions refer to the tree of figure which node is the rootb what are the internal nodesc how many descendants does node cs haved how many ancestors does node cs havee what are the siblings of node homewo...
13,084
- find the value of the arithmetic expression associated with each subtree of the binary tree of figure - draw an arithmetic expression tree that has four external nodesstoring the numbers and (with each number stored in distinct external nodebut not necessarily in this order)and has three internal nodeseach storing an...
13,085
- in what order are positions visited during postorder traversal of the tree of figure - let be an ordered tree with more than one node is it possible that the preorder traversal of visits the nodes in the same order as the postorder traversal of if sogive an exampleotherwiseexplain why this cannot occur likewiseis it ...
13,086
- let be (not necessarily properbinary tree with nodesand let be the sum of the depths of all the external nodes of show that if has the minimum number of external nodes possiblethen is (nand if has the maximum number of external nodes possiblethen is ( log nc- let be (possibly improperbinary tree with nodesand let be ...
13,087
- describe how to clone linkedbinarytree instance representing proper binary treewith use of the attach method - describe how to clone linkedbinarytree instance representing (not necessarily properbinary treewith use of the add left and add right methods - we can define binary tree representation for an ordered general...
13,088
- given proper binary tree define the reflection of to be the binary tree such that each node in is also in but the left child of in is ' right child in and the right child of in is ' left child in show that preorder traversal of proper binary tree is the same as the postorder traversal of ' reflectionbut in reverse or...
13,089
sales domestic international canada america africa overseas europe (aasia australia sales domestic international canada america overseas africa europe asia australia (bfigure (atree (bindented parenthetic representation of - the indented parenthetic representation of tree is variation of the parenthetic representation ...
13,090
- note that the build expression tree function of the expressiontree class is written in such way that leaf token can be any stringfor exampleit parses the expression ( *( + )howeverwithin the evaluate methodan error would occur when attempting to convert leaf token to number modify the evaluate method to accept an opt...
13,091
(ac (bfigure (aslicing floor plan(bslicing tree associated with the floor plan of the basic rectangles namelythis problem requires the assignment of values (pand (pto each position of the slicing tree such thatif is leaf whose basic rectangle has minimum width if is an internal positionassociated with max( () ( ) hori...
13,092
- write program that can play tic-tac-toe effectively (see section to do thisyou will need to create game tree which is tree where each position corresponds to game configurationwhichin this caseis representation of the tic-tac-toe board (see section the root corresponds to the initial configuration for each internal p...
13,093
priority queues contents the priority queue abstract data type priorities the priority queue adt implementing priority queue the composition design pattern implementation with an unsorted list implementation with sorted list heaps the heap data structure implementing priority queue with heap array-based representation ...
13,094
the priority queue abstract data type priorities in we introduced the queue adt as collection of objects that are added and removed according to the first-infirst-out (fifoprinciple company' customer call center embodies such model in which waiting customers are told "calls will be answered in the order that they were ...
13,095
the priority queue adt formallywe model an element and its priority as key-value pair we define the priority queue adt to support the following methods for priority queue pp add(kv)insert an item with key and value into priority queue min)return tuple( , )representing the key and value of an item in priority queue with...
13,096
implementing priority queue in this sectionwe show how to implement priority queue by storing its entries in positional list (see section we provide two realizationsdepending on whether or not we keep the entries in sorted by key the composition design pattern one challenge in implementing priority queue is that we mus...
13,097
implementation with an unsorted list in our first concrete implementation of priority queuewe store entries within an unsorted list our unsortedpriorityqueue class is given in code fragment inheriting from the priorityqueuebase class introduced in code fragment for internal storagekey-value pairs are represented as com...
13,098
class unsortedpriorityqueue(priorityqueuebase)base class defines item """ min-oriented priority queue implemented with an unsorted list "" nonpublic utility def find min(self) """return position of item with minimum key ""is empty inherited from base class if self is empty) raise emptypriority queue is empty small self...
13,099
implementation with sorted list an alternative implementation of priority queue uses positional listyet maintaining entries sorted by nondecreasing keys this ensures that the first element of the list is an entry with the smallest key our sortedpriorityqueue class is given in code fragment the implementation of min and...