id
int64
0
25.6k
text
stringlengths
0
4.59k
14,000
stacks exit as we move through the mazewe must remember the path we took in order to backtrack when reaching dead end stack provides the ideal structure we need to remember our path as we move forward in the mazewe can push our current position onto the stack using cellposition object before moving forward to the next ...
14,001
consider our implementation of the stack adt using the python listand suppose we had used the front of the list as the top of the stack and the end of the list as the base what impactif anywould this have on the run time of the various stack operations show that all of the stack adt operations have constant time in the...
14,002
stacks top of the stack implement the operations of the postfix calculator adt as defined herepostfixcalculator()creates new postfix calculator with an empty operand stack valuex )pushes the given operand onto the top of the stack result()returns an alias to the value currently on top of the stack if the stack is empty...
14,003
queues the term queue is commonly defined to be line of people waiting to be served like those you would encounter at many business establishments each person is served based on their position within the queue thusthe next person to be served is the first in line as more people arrivethey enter the queue at the back an...
14,004
queues define queue adt queue is data structure that linear collection of items in which access is restricted to first-in first-out basis new items are inserted at the back and existing items are removed from the front the items are maintained in the order in which they are added to the structure queue()creates new emp...
14,005
dequeue( enqueue( enqueue( figure abstract view of the queue after performing additional operations empty queue by examining the length of the list the complete python list-based implementation is provided in listing and an instance of the class is illustrated in figure on the next page to enqueue an itemwe simply appe...
14,006
queues qlist queue (pylistfigure an instance of the queue adt implemented using python list element of the list before attempting to remove an item from the listwe must ensure the queue is not empty rememberthe queue definition prohibits the use of the dequeue(operation on an empty queue thusto enforce thiswe must firs...
14,007
data organization to implement queue as circular arraywe must maintain count field and two markers the count field is necessary to keep track of how many items are currently in the queue since only portion of the array may actually contain queue items the markers indicate the array elements containing the first and las...
14,008
queues back front front back count the queue now contains seven items in elements [ with one empty slot what happens if value is addedsince we are using circular arraythe same procedure is used and the new item will be inserted into the position immediately following the back marker in this casethat position will be el...
14,009
listing the arrayqueue py module implementation of the queue adt using circular array from array import array class queue creates an empty queue def __init__selfmaxsize self _count self _front self _back maxsize self _qarray arraymaxsize returns true if the queue is empty def isemptyself return self _count = returns tr...
14,010
queues back front front back count figure the circular array when the queue is first created in the constructor into the position immediately following the back marker but rememberwe are using circular array and once the marker reaches the last element of the actual linear arrayit must wrap around to the first element ...
14,011
require complete traversal to find the end of the list figure illustrates sample linked list with the two external references size qtail qhead queue (linkedfigure an instance of the queue adt implemented as linked list the complete implementation of the queue adt using linked list with tail reference is provided in lis...
14,012
queues listing continued self _qhead self _qhead next self _count - return node item private storage class for creating the linked list nodes class _queuenodeobject )def __init__selfitem )self item item self next none priority queues some applications require the use of queue in which items are assigned priority and th...
14,013
length ()returns the number of items currently in the queue enqueueitempriority )adds the given item to the queue by inserting it in the proper position based on the given priority the priority value must be within the legal range when using bounded priority queue dequeue()removes and returns the front item from the qu...
14,014
queues implementationunbounded priority queue there are number of ways to implement an unbounded priority queue adt the most basic is to use python list or linked list as was done with the queue adt to implement the priority queuewe must consider several facts related to the definition of the adta priority must be asso...
14,015
the proper ordering of items with equal prioritythe enqueue operation must ensure newer items are inserted closer to the front of the list than the other items with the same priority an implementation of the priority queue using python list in which new items are appended to the end is provided in listing sample instan...
14,016
queues priorityqentry qlist priorityqueue (list "purple"purple "black"black "orange"orange "white"white "green"green "yellowfigure an instance of the priority queue implemented using list to evaluate the efficiencywe consider the implementation of each operation testing for an empty queue and determining the size can b...
14,017
as with the python list implementation of the priority queuetesting for an empty queue and determining the size can be done in ( time the enqueue operation can also be done in constant time since we need only append new node to the end of the list the dequeue operationhoweverrequires (ntime since the entire list must b...
14,018
queues the implementation of the priority queue using an array of queues is also quite simple but can we obtain constant time operationswe begin with the isempty(and len operations since data field is maintained to store the number of items in the priority queueboth can be performed in constant time the enqueue operati...
14,019
we can safely treat as constant value and specify the dequeue operation as requiring constant time the disadvantage of this structure for the implementation of the priority queue is that the number of levels is fixed if an application requires priority queue with an unlimited number of priority levelsthen the vector or...
14,020
queues queuing system model we can model queuing system by constructing discrete event simulation the simulation is sequence of significant events that cause change in the system for examplein our airline ticket counter simulationthese events would include customer arrivalthe start or conclusion of transactionor custom...
14,021
customer arrives during the current tick of the clock in real-world systemthis event cannot be directly controlled but is true random act we need to model this action as close as possible in our simulation simple approach would be to flip coin and let "headsrepresent customer arrival but this would indicate that there ...
14,022
queues for simplicity we use minutes as the discrete time units this would not be sufficient to simulate real ticket counter as multiple passengers are likely to arrive within any given minute the program will then perform the simulation and produce the following outputnumber of passengers served number of passengers r...
14,023
passenger class firstwe need class to store information related to single passenger we create passenger class for this purpose the complete implementation of this class is provided in listing the class will contain two data fields the first is an identification number used in the output of the event information the sec...
14,024
queues determine if the agent is free the isfinished(method is used to determine if the passenger currently being served by this agent has completed her transaction this method only flags the transaction as having been completed to actually end the transactionstopservice(must be called stopservice(sets the passenger fi...
14,025
listing the simulation py module implementation of the main simulation class from array import array from llistqueue import queue from people import ticketagentpassenger class ticketcountersimulation create simulation object def __init__selfnumagentsnumminutesbetweentimeservicetime )parameters supplied by the user self...
14,026
queues used to represent the line in which passengers must wait until they are served by ticket agent the ticket agents are represented as an array of agent objects the individual objects are instantiated and each is assigned an id numberstarting with two data fields are needed to store data collected during the actual...
14,027
num minutes num agents average service time between average wait passengers served passengers remaining table sample results of the ticket counter simulation experiment hand execute the following code and show the contents of the resulting queuevalues queue(for in range if = values enqueuei hand execute the following c...
14,028
queues programming projects implement the priority queue adt using each of the following(asorted python list (bsorted linked list (cunsorted linked list deque (pronounced "deck"is similar to queueexcept that elements can be enqueued at either end and dequeued from either end define deque adt and then provide an impleme...
14,029
advanced linked lists in we introduced the linked list data structure and saw how it can be used to improve the construction and management of lists for certain types of applications in that discussionwe limited the focus to the singly linked list in which traversals start at the front and progressone element at timein...
14,030
advanced linked lists to the preceding nodeas illustrated in figure to create the individual nodeswe must add third field to the node classwhich we name dlistnode to reflect its use with doubly linked listas shown in listing listing storage class for doubly linked list node class dlistnode def __init__selfdata )self da...
14,031
beginning to end is identical to that with singly linked list we start at the node referenced by head and advance the temporary referencecurnodeone node at timeusing the next link field the reverse traversalprovided in listing starts at the node referenced by tail and advances curnodeone node at timeusing the prev link...
14,032
advanced linked lists referencesheadtailand probelisting provides an implementation for searching sorted doubly linked list using the probing technique listing probing doubly linked list given the headtailand probe referencesprobe the list for target make sure the list is not empty if head is none return false if probe...
14,033
sal is performedotherwise normal forward traversal is used if the target is found during the iteration of the appropriate loopthe function is terminated and true is returned otherwisethe loop will terminate after exhausting all possible nodes or stopping early when it' determined the target cannot possibly be in the li...
14,034
advanced linked lists head tail figure the result of inserting the new node into the doubly linked list figure illustrates the links required to insert node at the front or end of doubly linked list the code for adding node to sorted doubly linked list is provided in listing since tail reference is commonly used with d...
14,035
listing inserting value into an ordered doubly linked list given head and tail reference and new valueadd the new value to sorted doubly linked list newnode dlistnodevalue if head is none empty list head newnode tail head elif value head data insert before head newnode next head head prev newnode head newnode elif valu...
14,036
advanced linked lists listref " " " " " "vlistref figure examples of circular linked lists single external reference variable is used to point to node within the list technicallythis could be any node in the listbut for conveniencethe external reference is commonly set to the last node added to the list by referencing ...
14,037
listing traversing circular linked list def traverselistref )curnode listref done listref is none while not done curnode curnode next print curnode data done curnode is listref of the loop is handled by the boolean variable donewhich is initialized based on the status of listref if the list is emptydone will be set to ...
14,038
advanced linked lists we must ensure this operation also works for list containing single nodeas illustrated in figure when curnode is advanced to the next nodeit actually still references itself this is appropriate since the node is both the first and last node in the list after the node is visited and the data printe...
14,039
adding nodes adding nodes to an ordered circular linked list is very similar to that of the ordered linear versions the major difference is the management of the loopback link from the last node to the first the implementation is much simpler if we divide it into four casesas illustrated in figure ( the list is empty w...
14,040
advanced linked lists listref curnode " (alistref " "anewnode " " " " " " " " (blistref " " " " " " " " " " newnode ( " "bprednode curnode listref " " newnode " " " " " (dfigure the links required to insert new node into circular list(ainserting the first node into an empty list(bprepending to the front(cappending to t...
14,041
multi-linked lists the doubly linked list is special instance of the more general multi-linked list multi-linked list is one in which each node contains multiple link fields which are used to create multiple chains within the same collection of nodes in the doubly linked listthere are two chains through the collection ...
14,042
advanced linked lists listing the node class for multi-linked list class studentmlistnode def __init__selfdata )self data data self nextbyid none self nextbyname none when inserting nodes into the multi-linked lista single node instance is createdbut two insertions are required after creating the new nodethe multi-link...
14,043
efficient solutions for many of the operations since traversals could be limited to per-row basis instead of complete traversal of all non-zero elements some matrix operations and applicationshoweverrequire traversals in column order instead of row order by organizing the non-zero elements based on the matrix rowsthe t...
14,044
advanced linked lists complex iterators the iterators designed and used in earlier were examples of simple iterators since we only needed to maintain single traversal variable more complex example would be the addition of an iterator to the sparsematrix class implemented as an array of linked lists in the previous or t...
14,045
every row in the sparse matrix does not necessarily contain elementswe must search for the first node this same operation will be required when advancing through the sparse matrix as we reach the end of each rowso we include the findnextelement(helper method to find the next node in the array of linked lists to find th...
14,046
advanced linked lists layout text editors typically work with an abstract view of the text document by assuming it is organized into rows and columns as illustrated in figure the physical storage of text document depends on the underlying data structurethough when stored on diskthe text file is simply sequential stream...
14,047
text within documentyou must fill the document with blank lines and spaces as necessary the minimum cursor movements available with most text editors includevertical movement in which the cursor is moved one or more lines up or down from the current line when the cursor is moved in the vertical directionit typically ma...
14,048
advanced linked lists the two operations is which character is deleted and what happens to the cursor afterward in the delete operationthe character at the cursor position is removed and the cursor remains at the same position the rub-out operationon the other handremoves the character preceding the cursor and then mov...
14,049
setentrymodeinsert )sets the entry mode to either insert or overwrite based on the value of the boolean argument insert toggleentrymode()toggles the entry mode to either insert or overwrite based on the current mode ininsertmode()returns true if the current entry mode is set to insert and false otherwise getchar()retur...
14,050
advanced linked lists addcharchar )inserts the given character into the buffer at the current position if the current entry mode is insertthe character is inserted and the following characters on that line are shifted downin overwrite modethe character at the current position is replaced if the cursor is currently at n...
14,051
lastline firstline curline curlinendx curcolndx numlines insertmode true editbuffer python list editbuffernode figure the doubly linked list of vectors used to implement the edit buffer adt representing the text document from figure partial implementation of the editbuffer class is provided in listing the implementatio...
14,052
advanced linked lists listing continued returns the number of characters in the current line def numcharsself )return lenself _curline text returns the index of the current row (first row has index def lineindexself )return self _currowndx returns the index of the current column (first col has index def columnindexself...
14,053
self moveup self movelineend(else self _curcolndx - moves the cursor to the front of the current line def movelinehomeself self _curcolndx moves the cursor to the end of the current line def movelineendself )self _curcolndx self numchars( starts new line at the cursor position def breaklineself )save the text following...
14,054
advanced linked lists listing continued defines private storage class for creating the list nodes class _editbuffernode def __init__selftext )self text text self prev none self next none constructor the constructor is defined in lines - of listing the firstline and lastline reference variables act as the head and tail ...
14,055
lines followed by curlinendx being adjusted appropriately finallywe determine if the horizontal position of the cursor must be adjusted if the line to which the cursor has been moved is shorter than the previous linethen the cursor must be positioned at the end of the new line horizontal movement of the cursor is manag...
14,056
advanced linked lists deleting newline character requires the merging of two linesthe current line with the following one of course the newline character of the last line in the buffer cannot be deleted thusthis condition must first be checked before merging the two lines merging the two lines requires several steps fi...
14,057
the contents at the end of the current line vector starting at the cursor position will form the new line we first extract and save this text by creating slice from the current line the part of the vector from which we created the slice is then deleted and newline character is appended we use the insertnode(helper meth...
14,058
advanced linked lists searchforstr )searches the buffer and returns tuple containing the (linecolposition of the first occurrence of the given search string none is returned if the buffer does not contain the search string searchforallstr )the same as searchfor(but returns vector of tuples indicating all occurrences of...
14,059
recursion recursion is process for solving problems by subdividing larger problem into smaller cases of the problem itself and then solving the smallermore trivial parts recursion is powerful programming and problem-solving tool it can be used with wide range of problems from basic traditional iterations to the more ad...
14,060
recursion the current sequential flow of execution is interrupted and control is transferred to the printrev(function with value of being assigned to argument the body of printrev(begins execution at the first statement since is greater than the body of the if statement is executed when the flow of execution reaches th...
14,061
properties of recursion local variables like any other functioneach call to recursive function creates new instances of all local reference variables used within that function changing the contents of local reference variable does not affect the contents of other instances of that variable was made from within the prin...
14,062
recursion typically occurs in each recursive call when the larger problem is divided into smaller parts the larger data set is subdivided into smaller sets or the larger term is reduced to smaller value by each recursive call in our recursive printing solutionthis progression is accomplished by subtracting one from the...
14,063
listing the fact(recursive function compute ndef factn )assert > "factorial not defined for negative values if return else return fact( recursive call trees figure used boxes to represent function invocations and to illustrate the flow of execution for two recursive functions the specific placement of the boxes illustr...
14,064
recursion if function makes multiple calls to other functionseach function call is indicated in the tree by box and directed edge the edges are listed left to right in the order the calls are made for examplesuppose we execute the following simple program that consists of three functions the resulting call tree is show...
14,065
leading to the foo( box since that function executes the return statementwe follow the dashed edge back to the main routine execution continues by following the next edge out of the main routine boxwhich leads us to the bar( function box from therewe continue to follow the directed edges between the boxes and eventuall...
14,066
recursion main( fib( fib( fib( fib( fib( fib( fib( fib( fib( fib( fib( fib( fib( fib( fib( figure recursive call tree for fib( the run time stack each time function is calledan activation record is automatically created in order to maintain information related to the function one piece of information is the return addr...
14,067
when the main routine is executedthe first activation record is created and pushed onto the run time stackas illustrated in figure (awhen the factorial function is calledthe second activation record is created and pushed onto the stackas illustrated in figure ( )and the flow of execution is changed to that function fac...
14,068
recursion using software stack using recursion in solving problems is very similar to using the software implemented stack structure in factany solution that can be implemented using stack structure can be implemented with recursionand vice versa consider the problem of printing in reverse order the items stored in sin...
14,069
to provide more efficient solution to the problema stack structure can be used to push the data values onto the stackone at timeas we traverse through the linked list thenthe items can be popped and printed resulting in the reverse order listing this solution is provided in listing and the resulting stack after the ite...
14,070
recursion as illustrated in figure (aif we carry this idea furtherthen each link in the list can be thought of as linking the node to sublist of nodesas illustrated in figure (bwith this view of the listwe can print the list in reverse order by recursively printing the sublist pointed to by the node and then printing t...
14,071
printlistnode next nodeprintlistnode next nodeprintlistnode next nodeprintlistnode next nodeprintlistnode next nodeprintlisthead nodeheadmain() run time stack figure the run time stack for the printlist(function when the base case is reached while processing the linked list from figure as the recursion progresses and m...
14,072
recursion problem returns for exampleconsider the function in listing which printed the contents of linked list in reverse order we had to save reference to each node until the recursive process began unwindingat which time the node values could be printed by using recursionthese references were automatically pushed on...
14,073
listing recursive implementation of the binary search algorithm performs recursive binary search on sorted sequence def recbinarysearchtargettheseqfirstlast )if the sequence cannot be subdivided furtherwe are done if first last base case # return false else find the midpoint of the sequence mid (last first/ does the el...
14,074
recursion recbinarysearch(values, , middle item recbinarysearch(values, , middle item recbinarysearch(values, , false log levels middle item recbinarysearch(values, , false figure the recursive call tree for the binary search algorithm (topwhen searching for value in the given sequence (bottomtowers of hanoi the towers...
14,075
how would you go about solving this problem recursivelyof course you need to think about the base casethe recursive caseand how each recursive call reduces the size of the problem we will derive all of these in timebut the easiest way to solve this problem is to think about the problem from the bottom up instead of thi...
14,076
recursion listing recursive solution for the towers of hanoi puzzle print the moves required to solve the towers of hanoi puzzle def movensrcdesttemp )if > moven srctempdest print"move % -% (srcdest)moven tempdestsrc to see how this recursive solution worksconsider the puzzle using three disks and the execution of the ...
14,077
pole pole pole start position move from pole to pole move from pole to pole move from pole to pole move from pole to pole figure the first four moves in solving the towers of hanoi puzzle with three disks
14,078
recursion move( , , , level number of calls move( - move( - move( - move( - move( - move( - move( move( - move( move( ** - figure the recursive call tree for the towers of hanoi puzzle with disks exponential operation some of the recursive examples we have seen are actually slower than an equivalent iterative version s...
14,079
power instead of computing as we can reduce the number of multiplications if we computed ( ) instead better yetwhat if we just computed this is the idea behind recursive definition for raising value to an integer power (the expression / is integer division in which the real result is truncated if / ( xif is even / ( xi...
14,080
recursion cannot visualize or evaluate this amount of information and instead must rely on experience in attempting to make the best moves consider the game of tic-tac-toe in which two players use board containing nine squares organized into three rows of three columnsthe two players take turns placing tokens of xs and...
14,081
the computer would need to evaluate all of these moves to determine which would be the best the decision would be based on which move would allow it to win before its opponent the next figure shows the part of the game tree that is constructed while evaluating the placement of an in the upper-right square upon evaluati...
14,082
recursion in this we have discovered that function calls and recursion are implemented internally using run time stack thusthe solution to any problem that requires the use of stack can be implemented using recursion in this sectionwe explore the well-known puzzle and classic recursion example known as the eightqueens ...
14,083
solving for four-queens to develop an algorithm for this problemwe can first study smaller instance of the problem by using just four queens and board how would you go about solving this smaller problemyou may attempt to randomly place the queens on the board until you find solution that may work for this smaller case ...
14,084
recursion which we first return to the second column and try alternate positions for that queen before possibly having to return all the way back to the first column the next step is to return to the second column and pick up the queen we placed at position ( and remove the markers that were used to indicate the square...
14,085
after picking up the queen in the first columnwe place it in the next position ( within that column we can now repeat the process and attempt to find open positions in each of the remaining columns these final stepswhich are illustrated hereresults in solution to the four-queens problem having found solution for the fo...
14,086
define recursion nqueens board adt the -queens board is used for positioning queens on square board for use in solving the -queens problem the board consists of squares arranged in rows and columnswith each square identified by indices in the range [ nqueensboardn )creates an empty board size()returns the size of the b...
14,087
listing the recursive function for solving the -queens problem def solvenqueensboardcol ) solution was found if -queens have been placed on the board if board numqueens(=board size(return true else find the next unguarded square within this column for row in rangeboard size()if board unguardedrowcol )place queen in tha...
14,088
recursion figure representing an board using - array figure in which three queens have been placed and we need to determine if the square at position ( is unguarded when searching horizontally backwardwe examine the elements of the - array looking for an index equal to that of the current row if one is foundthen there ...
14,089
exercises draw the recursive call tree for the printrev(function from section when called with value of determine the worst case run time of the recursive factorial function determine the worst case run time of the recursive fibonacci function show or prove that the printlist(function requires linear time does the recu...
14,090
recursion programming projects design and implement program to solve the -queens problem your program should prompt the user for the size of the boardsearch for solutionand print the resulting board if solution was found instead of finding single solution to the -queens problemwe can compute the total number of solutio...
14,091
hash tables the search problemwhich was introduced in attempts to locate an item in collection based on its associated search key searching is the most common operation applied to collections of data it' not only used to determine if an item is in the collectionbut can also be used in adding new items to the collection...
14,092
hash tables hundred products in the future soyou decide to assign unique identifier or code to each product using the integer values in the range to manage the data and allow for searchesyou decide to store the product codes in an array of sufficient size for the number of products available figure illustrates the cont...
14,093
** ** ** figure storing collection of product codes by direct mapping there is product with code and it can be directly accessed at array element if the target key is not in the collectionas is the case for product code the corresponding element ( will contain null reference this results in constant time search since w...
14,094
hash tables figure storing the first five keys in the hash table linear probing the first five keys were easily added to the table the resulting index values were unique and the corresponding table entries contained null referenceswhich indicated empty slots but that' not always the case consider what happens when we a...
14,095
when key is addedthe hash function maps the key to index but we just added key to this entry your first instinct may be to remove key from this locationsince did not map directly to this entryand store here instead once key is stored in the hash tablehoweverit' only removed when delete operation is performed this colli...
14,096
hash tables probe continues until the target is locateda null reference is encounteredor all slots have been examined when either of the latter two situations occursthis indicates the target key is not in the table figure illustrates the searches for key which is in the tableand key which is not in the table ( ( figure...
14,097
thuswhen probing to add new key or in searching for an existing keywe know the search must continue past the slot since the target may be stored beyond this point figure illustrates the correct way to delete key from the hash table the delta symbol is used to indicate deleted entry figure the correct way to delete key ...
14,098
hash tables where is the ith probe in the sequencei home is the home positionwhich is the index to which the key was originally mapped by the hash function the modulus operator is used to wrap back around to the front of the array after reaching the end the use of the linear probe resulted in six collisions in our hash...
14,099
nowconsider the case where the table size is and the constant factor is the probe sequence will only include the even numbered entries and will repeat the same sequence without possibly finding the key or an available entry to store new key quadratic probing the linear probe with constant factor larger than spreads the...