id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
21,900 | 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... |
21,901 | 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... |
21,902 | 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... |
21,903 | 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... |
21,904 | 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... |
21,905 | - 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... |
21,906 | 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 ... |
21,907 | - 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... |
21,908 | - 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... |
21,909 | 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... |
21,910 | 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... |
21,911 | 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... |
21,912 | 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... |
21,913 | 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 ... |
21,914 | 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... |
21,915 | 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 ... |
21,916 | 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... |
21,917 | 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... |
21,918 | 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... |
21,919 | 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 ... |
21,920 | 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... |
21,921 | 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... |
21,922 | 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... |
21,923 | 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 ... |
21,924 | 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... |
21,925 | 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... |
21,926 | 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... |
21,927 | 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... |
21,928 | 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... |
21,929 | 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... |
21,930 | 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... |
21,931 | 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... |
21,932 | 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... |
21,933 | 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... |
21,934 | 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... |
21,935 | 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... |
21,936 | 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... |
21,937 | 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 ... |
21,938 | 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... |
21,939 | 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... |
21,940 | 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... |
21,941 | 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... |
21,942 | 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... |
21,943 | 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... |
21,944 | 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... |
21,945 | 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... |
21,946 | 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... |
21,947 | 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... |
21,948 | 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... |
21,949 | - 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 ... |
21,950 | 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... |
21,951 | - 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... |
21,952 | - 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... |
21,953 | 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... |
21,954 | 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 "... |
21,955 | 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... |
21,956 | 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... |
21,957 | 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... |
21,958 | 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... |
21,959 | 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... |
21,960 | 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... |
21,961 | 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 ... |
21,962 | 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 ... |
21,963 | 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... |
21,964 | 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... |
21,965 | 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... |
21,966 | 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... |
21,967 | 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... |
21,968 | 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... |
21,969 | 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... |
21,970 | 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 ... |
21,971 | 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... |
21,972 | 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... |
21,973 | 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... |
21,974 | 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... |
21,975 | 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 ... |
21,976 | 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... |
21,977 | 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... |
21,978 | 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... |
21,979 | 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... |
21,980 | 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... |
21,981 | 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... |
21,982 | 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... |
21,983 | 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... |
21,984 | 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 ... |
21,985 | 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... |
21,986 | 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 ... |
21,987 | 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... |
21,988 | 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... |
21,989 | 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... |
21,990 | 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... |
21,991 | 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... |
21,992 | 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 ... |
21,993 | 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... |
21,994 | 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... |
21,995 | 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... |
21,996 | 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... |
21,997 | 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... |
21,998 | 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... |
21,999 | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.