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 cell when reaching dead endwe can backtrack by popping the previous position from the stack and backing up to that position the implementation of this method is left as an exercise along with the reset(and draw(methods exercises hand execute the following code segment and show the contents of the resulting stack values stack(for in range if = values pushi hand execute the following code segment and show the contents of the resulting stack values stack(for in range if = values pushi elif = values pop( translate each of the following infix expressions into postfix ( ( bc (dv (ba ( cd (ea ( ( ( zv translate each of the infix expressions in exercise to prefix notation translate each of the following postfix expressions into infix (aa (dx (ba (ea (ca
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 worst case when implemented as linked list would it buy us anything to use tail reference with the linked list structure used to implement the stack adtexplain your answer evaluate the run time of the isvalidsource(function where is the number of characters in the +source file programming projects write and test program that extracts postfix expressions from the userevaluates the expressionand prints the results you may require that the user enter numeric values along with the operators and that each component of the expression be separated with white space the isvalidsource(function can be used to evaluate +source filebut it is incomplete brackets encountered inside comments and literal strings would not be paired with those found elsewhere in the program (ac+comments can be specified using //which starts comment that runs to the end of the current lineand the token pair /*/which encloses comment that can span multiple lines extend the function to skip over brackets found inside +comments (bc+literal strings are denoted by enclosing characters within double quotes ("string"and literal characters are denoted by enclosing character within single quotes (' 'extend the function to skip over brackets found inside +literal strings and characters design and implement function that evaluates prefix expression stored as text string implement the findpath()reset()and draw(methods for the maze class implement complete maze solving application using the components introduced earlier in the modify the solve(method to return vector containing tuples representing the path through the maze we can design and build postfix calculator that can be used to perform simple arithmetic operations the calculator consists of single storage component that consists of an operand stack the operations performed by the stack always use the top two values of the stack and store the result back on 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 emptynone is returned clear()clears the entire contents of the stack clearlast()removes the top entry from the stack and discards it computeop )removes the top two values from the stack and applies the given operation on those values the first value removed from the stack is the righthand side operand and the second is the lefthand side operand the result of the operation is pushed back onto the stack the operation is specified as string containing one of the operators * extend the postfix calculator adt as follows(ato perform several unary operations commonly found on scientific calculatorsabsolute valuesquare rootsinecosineand tangent the operations should be specified to the compute(method using the following acronymsabssqrtsincostan (bto use second stack on which values can be saved add the following two operations to the adtstore()removes the top value from the operand stack and pushes it onto the save stack recall()removes the top value from the save stack and pushes it onto the operand stack design and implement complete program that uses the postfix calculator adt to perform various operations extracted from the user the user enters text-based commandsone per linethat should be performed by the calculator for exampleto compute the user would enter the following sequence of commandsenter enter mul result which would result in being displayed your program should respond to the following set of commandsenterclrclrlastresultaddsubmuldivpow
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 and wait their turn queue structure is well suited for problems in computer science that require data to be processed in the order in which it was received some common examples include computer simulationscpu process schedulingand shared printer management you are familiar with printer queue if you have used shared printer many people may want to use the printerbut only one thing can be printed at time instead of making people wait until the printer is not being used to print their documentmultiple documents can be submitted at the same time when document arrivesit is added to the end of the print queue as the printer becomes availablethe document at the front of the queue is removed and printed the queue adt queue is specialized list with limited number of operations in which items can only be added to one end and removed from the other queue is also known as first-infirst-out (fifolist consider figure which illustrates an abstract view of queue new items are inserted into queue at the back while existing items are removed from the front even though the illustration shows the individual itemsthey cannot be accessed directly the definition of the queue adt follows front back figure an abstract view of queue containing five items
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 empty queuewhich is queue containing no items isempty()returns boolean value indicating whether the queue is empty length ()returns the number of items currently in the queue enqueueitem )adds the given item to the back of the queue dequeue()removes and returns the front item from the queue an item cannot be dequeued from an empty queue using the formal definition of the queue adtwe can now examine the code necessary to create the queue in figure queue( enqueue enqueue enqueue enqueue enqueue after creating queue objectwe simply enqueue the five values in the order as they appear in the queue we can then remove the values or add additional values to the queue figure illustrates the result of performing several additional operations on the sample queue implementing the queue since the queue data structure is simply specialized listit is commonly implemented using some type of list structure there are three common approaches to implementing queueusing vectora linked listor an array in the following sectionswe examine and compare these three approaches using python list the simplest way to implement the queue adt is to use python' list it provides the necessary routines for adding and removing items at the respective ends by applying these routineswe can remove items from the front of the list and append new items to the end to use list for the queue adtthe constructor must define single data field to store the list that is initially empty we can test for an
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 append it to the end of the list the dequeue operation can be implemented by popping and returning the item in the first listing the pylistqueue py module implementation of the queue adt using python list class queue creates an empty queue def __init__self )self _qlist list(returns true if the queue is empty def isemptyself )return lenself = returns the number of items in the queue def __len__self )return lenself _qlist adds the given item to the queue def enqueueselfitem )self _qlist appenditem removes and returns the first item in the queue def dequeueself )assert not self isempty()"cannot dequeue from an empty queue return self _qlist pop
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 first assert the queue is not empty and raise an exceptionwhen the operation is attempted on an empty queue since we use list operations to implement the individual queue operationswe need only recall the worst case times for the python list operations the size and empty condition operations only require ( time the enqueue operation requires (ntime in the worst case since the list may need to expand to accommodate the new item when used in sequencethe enqueue operation has an amortized cost of ( the dequeue operation also requires (ntime since the underlying array used to implement the python list may need to shrink when an item is removed in additionwhen an item is removed from the front of the listthe following items have to be shifted forwardwhich requires linear time no matter if an expansion occurs or not using circular array the list-based implementation of the queue adt is easy to implementbut it requires linear time for the enqueue and dequeue operations we can improve these times using an array structure and treating it as circular array circular array is simply an array viewed as circle instead of line an example is illustrated in figure figure the abstract view of circular array (leftand the physical view (righta circular array allows us to add new items to queue and remove existing ones without having to shift items in the process unfortunatelythis approach introduces the concept of maximum-capacity queue that can become full circular array queue implementation is typically used with applications that only require small-capacity queues and allows for the specification of maximum size
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 last items in the queue consider the following circular arrayfront front back count back which illustrates the implementation of the queue from figure the figure shows the corresponding abstract and physical views of the circular array new items are added to the queue by inserting them in the position immediately following the back marker the marker is then advanced one position and the counter is incremented to reflect the addition of the new item for examplesuppose we enqueue value into the sample queue the back marker is advanced to position and value is insertedfront back front back count to dequeue an itemthe value in the element marked by front will be returned and the marker is advanced one positionfront back front back count notice the remaining items in the queue are not shifted insteadonly the front marker is moved nowsuppose we add values and to the queue these values are added in the positions following the back marker
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 element thusthe queue wraps around the circular array as items are added and removedwhich eliminates the need to shift items the resulting queue is shown hereback front front back count this also represents full queue since all slots in the array are filled no additional items can be added until existing items have been removed this is change from the original definition of the queue adt and requires an additional operation to test for full queue queue implementation given the description of circular array and its use in implementing queuewe turn our attention to the implementation details python implementation of the queue adt using circular array is provided in listing the constructor creates an object containing four data fieldsincluding the counter to keep track of the number of items in the queuethe two markersand the array itself sample instance of the class is illustrated in figure for the circular queuethe array is created with maxsize elements as specified by the argument to the constructor the two markers are initialized so the first item will be stored in element this is achieved by setting front to and back to the index of the last element in the array when the first item is addedback count front back qarray queue (array figure queue object implemented as circular array
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 true if the queue is full def isfullself return self _count =len(self _qarrayreturns the number of items in the queue def __len__self return self _count adds the given item to the queue def enqueueselfitem )assert not self isfull()"cannot enqueue to full queue maxsize len(self _qarrayself _back (self _back maxsize self _qarray[self _backitem self _count + removes and returns the first item in the queue def dequeueself )assert not self isempty()"cannot dequeue from an empty queue item self _qarrayself _front maxsize len(self _qarrayself _front (self _front maxsize self _count - return item will wrap around to element and the new value will be stored in that position figure illustrates the circular array when first created by the constructor the size(and isempty(methods use the value of count to return the appropriate result as indicated earlierimplementing the queue adt as circular array creates the special case of queue with maximum capacitywhich can result in full queue for this implementation of the queuewe must add the isfull(methodwhich can be used to test if the queue is full againthe count field is used to determine when the queue becomes full to enqueue an itemas shown in lines - we must first test the precondition and verify the queue is not full if the condition is metthe new item can be inserted
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 this can be done using condition statement to test if back is referencing the last element and adjusting it appropriatelyas shown hereself _back + if self _back =lenself _qarray self _back simpler approach is to use the modulus operator as part of the increment step this reduces the need for the conditional and automatically wraps the marker to the beginning of the array as followsself _back self _back lenself _qarray the dequeue operation is implemented in similar fashion as enqueue(as shown in lines - of listing the item to be removed is taken from the position marked by front and saved the marker is then advanced using the modulus operator as was done when enqueueing new item the counter is decremented and the saved item is returned run time analysis the circular array implementation provides more efficient solution than the python list the operations all have worst case time-complexity of ( since the array items never have to be shifted but the circular array does introduce the drawback of working with maximum-capacity queue even with this limitationit is well suited for some applications using linked list major disadvantage in using python list to implement the queue adt is the expense of the enqueue and dequeue operations the circular array implementation improved on these operationsbut at the cost of limiting the size of the queue better solution is to use linked list consisting of both head and tail references adding the tail reference allows for quick append operations that otherwise would
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 listing rememberthe individual nodes in the list contain the individual items in the queue when dequeueing an itemwe must unlink the node from the list but return the item stored in that node and not the node itself an evaluation of the time-complexities is left as an exercise listing the llistqueue py module implementation of the queue adt using linked list class queue creates an empty queue def __init__self )self _qhead none self _qtail none self _count returns true if the queue is empty def isemptyself )return self _qhead is none returns the number of items in the queue def __len__self )return self _count adds the given item to the queue def enqueueselfitem )node _queuenodeitem if self isempty(self _qhead node else self _qtail next node self _qtail node self _count + removes and returns the first item in the queue def dequeueself )assert not self isempty()"cannot dequeue from an empty queue node self _qhead if self _qhead is self _qtail self _qtail none (listing continued
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 the items with higher priority are dequeued first howeverall items with the same priority still obey the fifo principle that isif two items with the same priority are enqueuedthe first in will be the first out the priority queue adt priority queue is simply an extended version of the basic queue with the exception that priority must be assigned to each item at the time it is enqueued there are two basic types of priority queuesbounded and unbounded the bounded priority queue assumes small limited range of priorities over the interval of integers [ pthe unbounded priority queue places no limit on the range of integer values that can be used as priorities the definition of the priority queue adt is provided below note that we use one definition for both bounded and unbounded priority queues define priority queue adt priority queue is queue in which each item is assigned priority and items with higher priority are removed before those with lower priorityirrespective of when they were added integer values are used for the priorities with smaller integer value having higher priority bounded priority queue restricts the priorities to the integer values between zero and predefined upper limit whereas an unbounded priority queue places no limits on the range of priorities priorityqueue()creates new empty unbounded priority queue bpriorityqueuenumlevels )creates new empty bounded priority queue with priority levels in the range from to numlevels isempty()returns boolean value indicating whether the queue is empty
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 queuewhich is the item with the highest priority the associated priority value is discarded if two items have the same prioritythen those items are removed in fifo order an item cannot be dequeued from an empty queue consider the following code segmentwhich enqueues number of items into priority queue the priority queue is defined with six levels of priority with range of [ the resulting queue is shown in figure bpriorityqueue enqueue"purple" enqueue"black" enqueue"orange" enqueue"white" enqueue"green" enqueue"yellow" ( "white( ( "black"black( ( "green( ( "orange"orange( ( "purple"purple( ( "yellow"yellowfigure abstract view of priority queue resulting from enqueueing several stringsalong with individual priorities the first item to be removed will be the first item with the highest priority notice when items "blackand "greenare enqueued"greenfollows "blackin the queue even though they have the same priority since items with equal priority still obey the fifo principle the following code segment removes the items and prints them to the terminalwhile not isempty(item dequeue(printitem which results in the following outputwhite black green orange purple yellow
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 associated with each item in the queuepossibly requiring the value to be stored along with the item the next item to be dequeued from the priority queue is the item with the highest priority if multiple items have the same prioritythose items must be dequeued in the order they were originally enqueued python list implementation we used python list to implement the basic queue earlier in the in that implementationthe queue items were organized within the list from front to back with new items appended directly to the end and existing items removed from the front that simple organization worked well with the basic queue when implementing the priority queuehoweverthe items cannot simply be added directly to the listbut instead we must have way to associate priority with each item this can be accomplished with simple storage class containing two fieldsone for the priority and one for the queue item for exampleclass _priorityqentry def __init__selfitempriority )self item item self priority priority with the use of storage class for maintaining the associated prioritiesthe next question is how should the entries be organized within the vectorwe can consider two approachesboth of which satisfy the requirements of the priority queueappend new items to the end of the list when new item is enqueuedsimply append new instance of the storage class (containing the item and its priorityto the end of the list when an item is dequeuedsearch the vector for the item with the lowest priority and remove it from the list if more than one item has the same prioritythe first one encountered during the search will be the first to be dequeued keep the items sorted within the list based on their priority when new item is enqueuedfind its proper position within the list based on its priority and insert an instance of the storage class at that point if we order the items in the vector from lowest priority at the front to highest at the endthen the dequeue operation simply requires the removal of the last item in the list to maintain
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 instance of the class is illustrated in figure note this implementation does not use the numlevels argument passed to the constructor since we can store items having any number of priority levels listing the priorityq py module implementation of the unbounded priority queue adt using python list with new items appended to the end class priorityqueue create an empty unbounded priority queue def __init__self )self _qlist list(returns true if the queue is empty def isemptyself )return lenself = returns the number of items in the queue def __len__self )return lenself _qlist adds the given item to the queue def enqueueselfitempriority )create new instance of the storage class and append it to the list entry _priorityqentryitempriority self _qlist appendentry removes and returns the first item in the queue def dequeueself assert not self isempty()"cannot dequeue from an empty queue find the entry with the highest priority highest self _qlist[ipriority for in rangeself len(see if the ith entry contains higher priority (smaller integerif self _qlist[ipriority highest highest self _qlist[ipriority remove the entry with the highest priority and return the item entry self _qlist pophighest return entry item private storage class for associating queue items with their priority class _priorityqentryobject )def __init__selfitemprioity )self item item self priority priority
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 be done in ( time the enqueue operation requires linear time in the worst case since the underlying array may have to be reallocatedbut it has ( amortized cost the dequeue operation is also (nsince we must search through the entire list in the worst case to find the entry with the highest priority linked list implementation singly linked list structure with both head and tail references can also be used to implement the priority queue as illustrated in figure the queuenode class used in the implementation of the queue adt using linked list has to be modified to include the priority value after thatthe linked list can be used in similar fashion as the python list when an item is enqueuedthe new node is appended to the end of the linked list and when dequeue operation is performedthe linked list is searched to find the entry with the highest priority we leave the actual design and implementation as an exercise but examine the time-complexity of this approach priorityqueue qhead size qhead "purple "black "orange"orange "white"white "green "yellow"yellowfigure implementation of the priority queue from figure using linked list
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 be searched in the worst case to find the entry with the highest priority once that entry is locatedthe node can be removed from the list in constant time implementationbounded priority queue the python list and linked list versions are quite simple to implement and can be used to implement the bounded priority queue but they both require linear time to dequeue an item since the priorities of bounded priority queue are restricted to finite set [ )we can improve this worst case time with an implementation in which all of the operations only require constant time this can be done using an array of queuesas illustrated in figure size qlevels bpriorityqueue "white"black"black"orange"orange"purple"purple"green"greenabstract view of the queues "yellow"yellowfigure implementation of the priority queue using an array of queues the implementation of the bounded priority queue adt is shown in listing the constructor creates two data fields the qlevels field contains an array of elements in which each contains an instance of the queue adt the size field maintains the number of items in the priority queuewhich can also be used to determine if the queue is empty when an item with priority is added to the priority queueit is added to the queue stored in the qlist[kelement to dequeue an item from the priority queuewe must iterate through the array to find the first non-empty queuewhich will contain the first item to be removed from the priority queue note that we do not have to store the priorities along with each item since all items with given priority will be stored in the same queue the priority can be determined from the array indices
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 operation also requires constant time since adding an item to general queue can be done in constant time as can accessing an individual queue in the array dequeueing from general queue implemented as linked list can be done in constant time but since we must iterate through the array to find the first non-empty queuethe priority dequeue operation requires (ptime while this time is linearit is linear with respect to the number of priorities and not to the number of elements in the queue (nwhen the number of priorities is quite smalllisting the bpriorityq py module implementation of the bounded priority queue adt using an array of queues in which the queues are implemented using linked list from array import array from llistqueue import queue class bpriorityqueue creates an empty bounded priority queue def __init__selfnumlevels )self _qsize self _qlevels arraynumlevels for in rangenumlevels self _qlevels[iqueue(returns true if the queue is empty def isemptyself )return lenself = returns the number of items in the queue def __len__self )return lenself _qsize adds the given item to the queue def enqueueselfitempriority )assert priority > and priority len(self _qlevels)"invalid priority level self _qlevels[priorityenqueueitem removes and returns the next item in the queue def dequeueself make sure the queue is not empty assert not self isempty()"cannot dequeue from an empty queue find the first non-empty queue len(self _qlevelswhile and not self _qlevels[iisempty( + we know the queue is not emptyso dequeue from the ith queue return self _qlevels[idequeue(
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 linked-list versions are better choice applicationcomputer simulations computers have long been used to model and simulate real-world systems and phenomena these simulations are simply computer applications that have been designed to represent and appropriately react to the significant events occurring in the system simulations can allow humans to study certain behaviors or experiment with certain changes and events in system to determine the appropriate strategy some of the more common simulations include weather forecasting and flight simulators flight simulatorwhich is mock-up of real cockpit and controlled by softwarehelps train pilots to deal with real situations without having to risk the life of the pilot or loss of the aircraft weather forecasts today are much more reliable due to the aide of computer simulations mathematical models have been developed to simulate weather patterns and atmospheric conditions these models can be solved using computer applicationswhich then provide information to meteorologists for use in predicting the weather computer simulations are also used for less glamorous applications businesses can use computer simulation to determine the number of employees needed to provide service to its customers for examplean airline may want to know how many ticket agents are needed at certain times of the day in order to provide timely service having too many agents will cost the airline moneybut too few will result in angry customers the company could simply study the customer habits at one airport and experiment with different number of agents at different times but this can be costly and time consuming in additionthe results may only be valid for that one airport to reduce the cost and allow for events that may occur at various airportsa computer simulation can be developed to model the real system airline ticket counter simulating an airline ticket counteror any other queuing system where customers stand in line awaiting serviceis very common queue structure is used to model the queuing system in order to study certain behaviors or outcomes some of the typical results studied include average waiting time and average queue length queuing systems that use single queue are easier to model more complex systems like those representing grocery store that use multiple queuesrequire more complex models in this textwe limit our discussion to single-queue systems
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 customer departure the simulation is time driven and performed over preset time period the passing of time is represented by loopwhich increments discrete time variable once for each tick of the clock the events can only occur at discrete time intervals thusthe time units must be small enough such that no event can occur between units simulation is commonly designed to allow the user to supply parameters that define the conditions of the system for discrete event simulation modeling queuing systemthese parameters includethe length of the simulation given in number of time units the simulation typically begins at time unit zero the number of servers providing the service to the customers we must have at least one server the expected service time to complete transaction the distribution of arrival timeswhich is used to determine when customers arrive by adjusting these parametersthe user can change the conditions under which the simulation is performed we can change the number of serversfor exampleto determine the optimal number required to provide satisfactory service under the given conditions finallya set of rules are defined for handling the events during each tick of the clock the specific rules depends on what results are being studied to determine the average time customers must wait in line before being servedthere are three rulesrule if customer arriveshe is added to the queue at mostone customer can arrive during each time step rule if there are customers waitingfor each free serverthe next customer in line begins her transaction rule for each server handling transactionif the transaction is completethe customer departs and the server becomes free when the simulation completesthe average waiting time can be computed by dividing the total waiting time for all customers by the total number of customers random events to correctly model queuing systemsome events must occur at random one such event is customer arrival in the first rule outlined earlierwe need to determine if
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 is / chance customer arrives every time unit this may be true for some systemsbut not necessarily the one we are modeling we could change and use six-sided die and let one of the sides represent customer arrival but this only changes the odds to in that customer arrives better approach is to allow the user to specify the odds of customer arriving at each time step this can be done in one of two ways the user can enter the odds customer arrives during the current time step as real value between (no chanceand ( sure thingif is enteredthen this would indicate there is in chance customer arrives instead of directly entering the oddswe can have the user enter the average time between customer arrivals we then compute the odds within the program if the user enters an average time of then on average customer arrives every minutes but customers can arrive during any minute of the simulation the average time between arrivals simply provides the average over the entire simulation we use the average time to compute the odds of customer arriving as or given the odds either directly by the user or computing them based on the average arrival timehow is this value used to simulate the random act of customer arrivingwe use the random number generator provided by python to generate number between and we compare this result to the probability (probof an arrival if the generated random number is between and prob inclusivethe event occurs and we signal customer arrival on the other handif the random value is greater than probthen no customer arrives during the current time step and no action is taken the arrival probability can be changed to alter the number of customers served in the simulation implementation we can design and implement discrete event computer simulation to analyze the average time passengers have to wait for service at an airport ticket counter the simulation will involve multiple ticket agents serving customers who have to wait in line until they can be served our design will be an object-oriented solution with multiple classes system parameters the program will prompt the user for the queuing system parametersnumber of minutes to simulate number of ticket agents average service time per passenger average time between passenger arrival
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 remaining in line the average wait time was minutes we will also have the program display event informationwhich can be used to help debug the program the debug information lists each event that occurs in the system along with the time the events occur for the input values shown abovethe event information displayed will betime time time time time time time time time time time time time time time time time time time time time time time time time time time time time time time time time time time time passenger arrived agent started serving passenger passenger arrived agent started serving passenger passenger arrived agent stopped serving passenger agent started serving passenger agent stopped serving passenger passenger arrived agent started serving passenger agent stopped serving passenger passenger arrived agent started serving passenger passenger arrived agent stopped serving passenger agent started serving passenger passenger arrived agent stopped serving passenger passenger arrived agent started serving passenger passenger arrived agent stopped serving passenger agent started serving passenger agent stopped serving passenger passenger arrived agent started serving passenger passenger arrived agent stopped serving passenger agent started serving passenger agent stopped serving passenger agent started serving passenger passenger arrived agent stopped serving passenger agent started serving passenger passenger arrived agent stopped serving passenger
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 second field records the time the passenger arrives this value will be needed to determine the length of time the passenger waited in line before beginning service with an agent methods are also provided to access the two data fields an instance of the class is illustrated in figure listing the passenger class defined in the simpeople py module used to store and manage information related to an airline passenger class passenger creates passenger object def __init__selfidnumarrivaltime )self _idnum idnum self _arrivaltime arrivaltime gets the passenger' id number def idnumself return self _idnum gets the passenger' arrival time def timearrivedself return self _arrivaltime ticket agent class we also need class to represent and store information related to the ticket agents the information includes an agent identification number and timer to know when the transaction will be completed this value is the sum of the current time and the average time of the transaction as entered by the user finallywe need to keep track of the current passenger being served by the agent in order to identify the specific passenger when the transaction is completed the ticketagent class is implemented in listing and an instance of the class is shown in figure the passenger field is set to null referencewhich will be used to flag free agent the idnum(method simply returns the id assigned to the agent when the object is created while the isfree(method examines the passenger field to idnum arrivaltime passenger idnum stoptime passenger ticketagent figure sample passenger and ticketagent objects
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 field to none to again indicate the agent is free and returns the passenger object to begin transactionstartservice(is calledwhich assigns the appropriate fields with the supplied arguments listing the ticketagent class defined in the simpeople py module used to store and manage information related to an airline ticket agent class ticketagent creates ticket agent object def __init__selfidnum )self _idnum idnum self _passenger none self _stoptime - gets the ticket agent' id number def idnumself )return self _idnum determines if the ticket agent is free to assist passenger def isfreeself )return self _passenger is none determines if the ticket agent has finished helping the passenger def isfinishedselfcurtime )return self _passenger is not none and self _stoptime =curtime indicates the ticket agent has begun assisting passenger def startserviceselfpassengerstoptime )self _passenger passenger self _stoptime stoptime indicates the ticket agent has finished helping the passenger def stopserviceself )thepassenger self _passenger self _passenger none return thepassenger simulation class finallywe construct the ticketcountersimulation classwhich is provided in listing to manage the actual simulation this class will contain the various componentsmethodsand data values required to perform discrete event simulation sample instance is illustrated in figure the first step in the constructor is to initialize three simulation parameters note the arriveprob is the probability of passenger arriving during the current time step using the formula described earlier queue is createdwhich will be
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 _arriveprob betweentime self _servicetime servicetime self _numminutes numminutes simulation components self _passengerq queue(self _theagents arraynumagents for in rangenumagents self _theagents[iticketagent( + computed during the simulation self _totalwaittime self _numpassengers run the simulation using the parameters supplied earlier def runself )for curtime in range(self _numminutes self _handlearrivalcurtime self _handlebeginservicecurtime self _handleendservicecurtime print the simulation results def printresultsself )numserved self _numpassengers len(self _passengerqavgwait floatself _totalwaittime numserved print"print"number of passengers served "numserved print"number of passengers remaining in line %dlen(self _passengerqprint"the average wait time was % minutes avgwait the remaining methods that have yet to be implemented def _handlearrivecurtime )handles simulation rule # def _handlebeginservicecurtime )handles simulation rule # def _handleendservicecurtime )handles simulation rule # ticketcountersimulation theagents passengerq numminutes arriveprob servicetime totalwaittime numpassengers figure sample ticketcountersimulation object
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 simulation the first is the summation of the time each passenger has to wait in line before being servedand the second keeps track of the number of passengers in the simulation the latter will also be used to assign an id to each passenger the simulation is performed by calling the run(methodwhich simulates the ticking of the clock by performing count-controlled loop keeping track of the current time in curtime the loop executes until numminutes have elapsed the events of the simulation are also performed during the terminating minutehencethe need for the numminutes in the range(function during each iteration of the loopthe three simulation rules outlined earlier are handled by the respective handlexyz(helper methods the handlearrival(method determines if passenger arrives during the current time step and handles that arrival handlebeginservice(determines if any agents are free and allows the next passenger(sin line to begin their transaction the handleendservice(determines which of the current transactions have completedif anyand flags passenger departure the implementation of the helper methods is left as an exercise after running the simulationthe printresults(method is called to print the results when the simulation terminates there may be some passengers remaining in the queue who have not yet been assisted thuswe need to determine how many passengers have exited the queuewhich indicates the number of passenger wait times included in the totalwaittime field the average wait time is simply the total wait time divided by the number of passengers served the last component of our program is the driver modulewhich is left as an exercise the driver extracts the simulation parameters from the user and then creates and uses ticketcountersimulation object to perform the simulation to produce the same results shown earlieryou will need to seed the random number generator with the value before running the simulationrandom seed in typical experimenta simulation is performed multiple times varying the parameters with each execution table illustrates the results of single experiment with multiple executions of the simulation note the significant change in the average wait time when increasing the number of ticket agents by one in the last two sets of experiments exercises determine the worst case time-complexity for each operation defined in the ticketcountersimulation class
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 code and show the contents of the resulting queuevalues queue(for in range if = values enqueuei elif = values dequeue( implement the remaining methods of the ticketcountersimulation class modify the ticketcountersimulation class to use seconds for the time units instead of minutes run an experiment with multiple simulations and produce table like table design and implement function that reverses the order of the items in queue your solution may only use the operations defined by the queue adtbut you are free to use other data structures if necessary
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 implementation for your definition design and implement todo list adt in which each entry can be assigned priority and the entries with the highest priority are performed first printers can be connected to the network and made available to many users to manage multiple print jobs and to provide fair accessnetworked printers use print queues designimplementand test computer program to simulate print queue that evaluates the average wait time modify your simulation from programming project to use priority queue for each print job the priorities should range from to with being the highest priority use random number generator to determine the priority of each job designimplementand test computer program to simulate telephone customer service center your simulation should evaluate the average time customers have to wait on hold designimplementand test computer program to simulate bank your simulation should evaluate the average time customers have to wait in line before they are served by teller redesign the ticketcounterclass to implement generic simulation class from which user can derive their own simulation classes designimplementand test computer program to simulate the checkout at grocery store your simulation must allow for multiple checkout lines and allow customers at the end of line to move to another checkout line this simulation differs from the one described in the for this simulationyou will have to accommodate the multiple checkout linesdecide how customer chooses lineand decide if and when customer moves to new checkout line
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 single direction but there are number of variations to the linked list structure based on how the nodes are linked and how many chains are constructed from those links in this we introduce some of the more common linked list variations the doubly linked list the singly linked list introduced in consists of nodes linked in single direction access and traversals begin with the first node and progress toward the last nodeone node at time but what if we want to traverse the nodes in reverse orderwith the singly linked listthis can be done but not efficiently we would have to perform multiple traversalswith each traversal starting at the front and stopping one node earlier than on the previous traversal or consider the problem in which you are given reference to specific node and need to insert new node immediately preceding that node since the predecessor of given node cannot be directly accessedwe would have to use modified insertion operation in which the list is traversed from the first node until the predecessor of the given node is found againthis is not an efficient solution for these operations and number of otherswe need direct access to both the node following and immediately preceding given node organization in doubly linked listeach node contains not only the data component and link to the next node as in the singly linked listbut also second link that points
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 data data self next none self prev none head reference is again used to reference the first node in the list tail referencealthough optionalis commonly used with doubly linked list to take advantage of the reverse chainwhich allows for traversals from back to front the last node is indicated by null reference in the next link of the last node as was done in the singly linked list but we must also indicate the first node since the list can be traversed in reverse order this is done using null reference in the prev link of the first node head tail figure doubly linked list with four nodes doubly linked list can be sorted or unsorted depending on the specific application the implementation of the various operations for an unsorted doubly linked list are very similar to those of the unsorted singly linked list we leave the implementation of these operations as an exercise and only focus on the use and management of sorted doubly linked lists list operations the position of the nodes in sorted doubly linked list are based on the key value of the corresponding data item stored in each node the basic linked list operations can also be performed on doubly linked list traversals the doubly linked list allows for traversals from front to back or back to front the traversals are performed using temporary external reference to mark the current node the only difference is which node we start with and which link field is used to advance the temporary reference traversing the doubly linked list from
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 field in either casethe traversal terminates when curnode is set to nullresulting in (nlinear time operation listing traversing doubly linked list in reverse order def revtraversaltail )curnode tail while curnode is not none printcurnode data curnode curnode prev searching searching for specific item in doubly linked listbased on key valuecan be implemented in the same fashion as for singly linked list start with the first node and iterate through the list until we find the target item or we encounter node containing key value larger than the target but doubly linked list provides an advantage not available in the singly linked list since we can move forward or backwardthe search operations do not have to begin with the first node suppose we perform sequence of search operations on the list from figure and we begin that sequence with search for value using the external reference probe to iterate through the listthe target is found in the third node if we leave probe pointing to the third nodeas illustrated in figure we can begin the next search operation where the previous search left off instead of starting over from the beginning suppose the next search is for value we can compare this target value to the item currently referenced by probe and determine if the search should proceed forward or backward starting from the probe node in this casewe search backwardusing probe to traverse the list thuseach time search is performedwe leave the probe reference where the previous search ended and use it for subsequent searches note that probe is not temporary reference variable as curnode was in the normal search operationbut must be maintained between operations in the same fashion as head and tail given the three external head probe tail figure probe reference positioned after searching for value
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 is nullinitialize it to the first node elif probe is none probe head if the target comes before the probe nodewe traverse backwardotherwise traverse forward if target probe data while probe is not none and target <probe data if target =probe data return true else probe probe prev else while probe is not none and target >probe data if target =probe data return true else probe probe next if the target is not found in the listreturn false return false as with singly linked listall of the list operations must also work with an empty listindicated by null head reference with the probe operationthe search simply fails if the list is empty this can be quickly determined by examining the head reference the probe reference can also be null at the beginning of the search operation this can occur when the first search is performedsince the probe reference has not been positioned within the list by previous search operation we could manage probe within the insert and deletion operations and make adjustments each time new node is added or deleted but performing this check within the search operation is just as easyespecially since this is the only operation in which probe is utilized the probe reference can also become null when the previous search fails after the traversal has exhausted all possible nodes and the external reference "falls off the list but unlike with null head referencethe search does not necessarily fail insteadthe probe reference must be initialized to point to the first node in the list to prepare for the current search the actual search is performed by either traversing forward or backward depending on the relation between the target and the key value in the node referenced by probe if the target is smaller than probe' keythen reverse sorted list traver
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 list in either casefalse is returned as the last operation of the function we can add quick test to determine if the target value cannot possibly be in the list this is done by comparing the target to the first and last nodes in the list if the target is smaller than the first item or larger than the lastwe know the search will ultimately fail since the target is not in the list this step can be omitted as the same results can be achieved by the search traversal followbut it can help to improve the search time on large lists the search operationwhich maintains and uses third external reference variablecan improve the search time for large number of sequential searches performed on large lists but in the worst caseit remains linear time operation since complete traversal may have to be performed adding nodes adding new nodes to sorted doubly linked list is done similar to that for the singly linked list the only difference is we do not need to keep track of the preceding node once the position for the new node is locatedwe can access its predecessor using the appropriate prev field consider figure which illustrates inserting new node into the middle of sorted doubly linked list the location of the new node is found by positioning single temporary external reference variable to point to the node containing the first value larger than the new value after this position is foundthe new node can be linked into the list using the various prev and next node fields as illustrated the resulting list after inserting the new node is illustrated in figure on the next page head curnode tail newnode figure linked modifications required to insert value into the doubly linked list as with singly linked listinserting node into non-empty sorted doubly linked list can occur in one of three placesat the frontat the endor somewhere in the middle inserting new node into the middle of list was illustrated above
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 doubly linked listwe can provide more efficient solution by dividing the operation into the four different cases this reduces the need for loop traversal when the list is empty or the new node is prepended or appended to the list head tail newnode (ahead tail (bnewnode figure the links required to insert new node into sorted doubly linked list at the (afront or (bback removing nodes deleting node from doubly linked list is done in similar fashion to that for singly linked list againthere is no need to position pred temporary external reference variable since the predecessor of given node can be accessed using the appropriate prev fields implementation of the delete operation is left as an exercise
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 value tail data insert after tail newnode prev tail tail next newnode tail newnode else insert in the middle node head while node is not none and node data value node node next newnode next node newnode prev node prev node prev next newnode node prev newnode the circular linked list another variation of the linked list structure is the circular linked list in which the nodes form continuous circle the circular linked list allows for complete traversal of the nodes starting with any node in the list it is also commonly used for applications in which data is processed in round-robin fashion for examplewhen scheduling the use of cputhe operating system must cycle through all of the processes running on computerallowing each an opportunity to use the processor for short period of time by using circular linked listthe choice of the next process is made in round-robin fashion organization the nodes in circular linked listas illustrated in figure are organized in linear fashion the same as those in singly or doubly linked list in facta circular linked list can have single or double links in singly linked versionevery node has successor while in doubly linked version every node has successor and predecessor the nodes in circular list have the same structure as those in the linear list versions the only difference is the next field of the last node links to the firstand in the doubly linked versionthe prev field of the first node links to the last
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 that nodewe have quick access to both the first node added and the last list operations the common set of operations performed on the linear versions of the linked list can also be performed on circular linked list howeversome modifications are required in the algorithm for each operation to take into account the location of the external reference variable and the fact that none of the nodes have null next field in this sectionwe describe the various list operations for use with sorted singly linked circular list these operations require only slight modifications when applied to an unsorted circular list or the doubly linked version traversals traversing circular linked list requires temporary external reference that is moved through the listone node at timejust like the linear versions for the circular listseveral modifications are requiredall of which are necessary in order to perform complete traversal while terminating the loop at the proper time terminating the loop is not as straightforward with the circular list since there are no nodes that have their next field set to none even in single-node listthe link field of the last node always points back to the first node we cannot simply initialize the curnode reference to the first node and traverse until it "falls offthe list as was done in the linear versions insteadwe need way to flag the end of the traversal independent of the link fields the algorithm for traversing circular linked list is provided in listing the traversal process begins by initializing curnode to reference the last node in the listas illustrated in figure (athe traversal reference begins at the last node instead of the first because we are going to terminate the traversal when it again reaches the last nodeafter iterating over the entire list the termination
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 false and the loop never executes when the list contains at least one nodedone will be initialized to true and the loop is executed in the linear versions of the linked listthe first step in the body of the loop was to visit the current node ( print the contents of the node data fieldand then advance the traversal reference to the next node in this versionwe must first advance curnodeas illustrated in figure ( )and then perform the visit operation remembercurnode is initialized to reference the last node in the list in order to begin the traversal with the first nodethe temporary reference must be advanced to the first node in the list " " " " " "tlistref curnode " " (acurnode listref " " " " " " " (bfigure traversing circular linked list(ainitial assignment of the temporary reference and (badvancement of the temporary reference to the first node in the list finallydone is updated by examining curnode to determine if it has again reached the last node in the listas referenced by the listref reference curnode was initialized to be an alias of listrefbut it was advanced at the beginning of the loop thuswhen curnode again reaches the end of the listwe know every node has been visited and the loop can terminate
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 printed in this examplecurnode is advanced once again when the alias test is performed at the bottom of the loopdone will be set to true and the loop will terminate properly listref curnode "bfigure traversing circular linked list containing single node searching the search operation requires traversal through the listalthough it can terminate early if we encounter the target item or reach an item larger than the target the implementationshown in listing closely follows that of the traversal operation from earlier listing searching circular linked list def searchcircularlistlistreftarget )curnode listref done listref is none while not done curnode curnode next if curnode data =target return true else done curnode is listref or curnode data target return false as with the traversal operationthe initialization of done handles the case where the list is empty and prevents the loop from ever being executed the modification of the done flag at the bottom of the loop handles the termination of the traversal when the target is not found compound logical expression is used in order to test both conditionsa complete traversal was performed or we reached an item larger than the target finallythe condition in the if statement handles the case where the target item is found in the list
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 when adding the node( the new node is inserted at the front( the new node is inserted at the endor ( the node is inserted somewhere in the middle the first three cases are straightforward and only require few adjustments in the links the fourth case requires search to find the proper location for the new node and the positioning of the two external reference variables this requires traversal similar to the one used earlier with the search operation the python code segment shown in listing provides the implementation of the insert operation it should be noted again that the illustrations show the ordering in which the links should be made to avoid accidentally unlinking and destroying existing nodes in the list listing inserting node into an ordered circular linked list given listref pointer and valueadd the new value to an ordered circular linked list newnode listnodevalue if listref is none empty list listref newnode newnode next newnode elif value listref next data insert in front newnode next listref next listref next newnode elif value listref data insert in back newnode next listref next listref next newnode listref newnode else insert in the middle position the two pointers prednodenone curnode listref done listref is none while not done prednode curnode prednode curnode next done curnode is listref or curnode data target adjust links to insert the node newnode next curnode prednode next newnode removing nodes deleting node from circular linked listfor both ordered and unordered listsclosely follows the steps required for inserting node into an ordered circular list the implementation of this operation is left as an exercise
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 the endand (dinserting in the middle
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 of nodeseach using the key field to form the chains the result is two singly linked lists in which one orders the nodes by key value in increasing order while the second orders the nodes in reverse order multiple chains in multi-linked listchains can be created using multiple keys or different data components to create the multiple links consider the example of student records introduced in suppose we want to create multi-linked list containing two chains in which the nodes are linked and sorted by id number in one chain and by name in the otheras illustrated in figure the first node in each chain is referenced by separate head pointer the listbyid reference indicates the first node in the chain sorted by id number while listbyname indicates the first node in the chain sorted by name for visual aidthe id chain is represented by solid lines and darker gray link fields while the name chain is represented by dashed lines and slightly lighter gray link fields listbyname smith smith john john east east main main st st somewhere somewhere va va roberts roberts susan susan quarry quarry rd rd nowhere nowhere tx tx listbyid smith smith jane jane rock rock rd rd valley valley view view md md brown brown steve steve nd nd st st ocean ocean city city ga ga figure multi-linked list storing student records with two complete chains the nodes in the multi-linked list can be traversed by either chainthe dashed links or the solid linksbased on the desired order it is up to the programmer to ensure he starts with the correct head node and follows the correct links to create multi-linked listthe nodes must contain multiple link fieldsone for each chain the studentmlistnode storage class in listing shows the definition used for the multi-linked list from figure
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-linked list is treated as two separate singly linked lists thusthe node must first be inserted into the chain ordered by id and then in the chain ordered by name similar action is required when deleting node from the multi-linked listbut in this casethe node must be removed from both chains in the previous examplethe two chains form two complete lists that isall of the nodes are part of both chains the second chain could form partial list instead for examplesuppose we wanted to create multi-linked list of student records with one chain sorted by id and another containing only those students whose last name is "smith,as illustrated in figure the former will contain all of the nodes and form complete listbut the latter will only contain subset of the nodes multi-linked lists can be organized in any number of ways with the resulting design based on the problem being solved second chain only includes students with last name "smithlistbyname smith smith john john east east main main st st somewhere somewhere va va roberts roberts susan susan quarry quarry rd rd nowhere nowhere tx tx listbyid smith smith jane jane rock rock rd rd valley valley view view md md brown brown steve steve nd nd st st ocean ocean city city ga ga figure multi-linked list storing with one complete chain and one partial chain the sparse matrix common use of multi-linked list is an alternative implementation of the sparse matrix adtwhich was introduced in earlier in we designed solution for the sparse matrix using python list to store the non-zero elements we improved on the original solution in by using an array of linked lists to store the non-zero elements with separate list for each row in the matrix while both improved on the - array implementationthe latter provided more
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 time required in these cases can actually be worse than with single linked list to provide convenient traversals of both rows and columnswe can use multilinked organizationas illustrated in figure the nodes are linked by two chains along the respective row and column this requires two arrays of linked listsone for the row lists and another for the column lists sparsematrix listofcols listofrows row col value figure multi-linked list implementation of the sparse matrix from figure an individual element can be accessed by traversing the row chain or the column chain as needed this dual access requires that each node contain both the row and column indices in addition to the two link fieldsas shown in listing the implementation of the sparse matrix adt using multi-linked list is left as an exercise listing the multi-linked nodes for implementing the sparse matrix adt class matrixmlistnode def __init__selfrowcolvalue self row row self col col self value value self nextcol none self nextrow none
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 the multi-linked list version defined in this both of those implementations used an array of linked lists to store the matrix elements to build an iterator in this casewe must keep track of the array of linked lists and both the current row within the array and the current node within the linked list for the given row listing provides an implementation of an iterator for the sparse matrix adt implemented using multi-linked list when the iterator is first createdthe constructor must initialize the currow and curnode fields to reference the first node in the first non-empty row since listing an iterator for the sparse matrix adt implemented using multi-linked list defines python iterator for the sparse matrix adt implemented using an array of linked lists class _sparsematrixiterator def __init__selfrowarray )self _rowarray rowarray self _currow self _curnode none self _findnextelement(def __iter__self )return self def nextself )if self _curnode is none raise stopiteration else value self _curnode value self _curnode self _curnode next if self _curnode is none self _findnextelement(return value def _findnextelementself ) self _currow while lenself _rowarray and self _rowarray[iis none + self _currow if lenself _rowarray self _currnode self _rowvector[ielse self _currnode none
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 the next nodethe helper method starts at the current row and increments counter until the next non-empty row is found or all rows have been processed if the counter references non-empty rowcurnode is set to the first node in that list otherwiseit is set to nonewhich will signal the end of the traversal loop the next(method of the sparsematrixiterator class need only examine the curnode field to determine if the stopiteration exception should be raised or value is to be returned if curnode is not nullwe first save the value from the current node and then advance the reference to the next node in the list when reaching the end of the linked list representing the current rowthe findnextelement(must be called to search for the next non-empty row in the array of linked lists the operation concludes by returning the value saved before advancing curnode to the next node applicationtext editor if you have used computerit' very likely you have used text editor text editors allow us to enter text to create documents or to enter information into form fields like those found on some web pages editors can be very complex like word processor or rather simple like microsoft' notepad no matter the complexityall text editors must maintain and manage the text as the user entersdeletesand manipulates characters and lines in this sectionwe define an edit buffer adtwhich can be used by simple text editor to store and manage the text of document being manipulated by the actual editor the adt is defined independent of the text editor and only contains operations necessary for the storage and manipulation of plain text this adt is not meant to be used by more complex editors such as those that perform syntax highlighting or even by word processorswhich must also maintain character properties like font style and size we conclude with an implementation of our edit buffer adt and discuss other alternatives typical editor operations while the design and implementation of an actual text editor is beyond the scope of this textbookthe examination of an edit storage buffer is not we begin our discussion by examining the workings of typical text editors that will aide in the design of our adt
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 of charactersas illustrated in figure the end of each line in text document contains newline character (\nresulting in rows of varying sizes of unlimited length an empty document is assumed to contain single blank line where blank line would consist of single newline character as visual aidthe illustrations in the two diagrams use the -symbol to indicate the actual location of the newline character and small bullet (*to indicate blank spaces def computesumthelist sum for value in thelist sum sum value return*sum def*computesum(*thelist*)***sum*=* **for*value*in*thelist*****sum*=*sum*+*value **return*sum figure the abstract view of text document as used by most text editors (topand the same with special characters inserted for the blank spaces and newlines (bottomdef*computesum(*thelist*)*:**sum*=* **for*value*in*thelist*:***figure the file or stream view of the text document from figure text cursor text editors also use the concept of cursor to mark the current position within the document the cursor position is identified by row and an offset or character position within the given row all basic insertion and deletion operations are performed relative to the cursor note that for this example we consider the cursor to be the keyboard or text cursor and not the cursor related to the use of the mouse the cursor can be moved and positioned anywhere within the documentbut only to spot currently containing character thus you cannot randomly place characters within document as if you were writing on piece of paper to position
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 maintains the same character position on the line to which it was moved if this line is shorter than the one from which the cursor was movedthe cursor is typically positioned at the end of the line horizontal movement along the current line in which the cursor moves either forward or backward when the cursor reaches the beginning of the lineit wraps backward to the end of the previous linewhen it reaches the end of the lineit wraps forward to the beginning of the next line thusthe cursor moves about the text document as if moving within stream of text like that stored in text file movement to the document and line extremes the cursor can typically be moved to the front or back of the current line or to the beginning or end of the document in the latter casethe cursor is typically moved to the front of the last row in the document inserting text most text editors use an entry mode of either "insert,in which new characters are inserted into the textor "overwrite,in which new characters replace existing characters in either modecharacters are inserted into the document at the cursor position when using insert modeall characters on the same line from the cursor to the end of the line are shifted down and the new character is inserted at the current position this differs from overwrite modein which new characters simply replace or overwrite the character at the cursor position in both casesthe cursor is then shifted one position to the right on the same line the newline characters that are used to indicate the end of line can be treated like any other character if new characters are inserted immediately before newline characterthe line is automatically extended when inserting text after newline characteryou are technically inserting the text at the beginning of the next line in front of the first character on that line when newline character is inserteda line break is created at the insertion pointresulting in the current line being split into two lines the new line is always inserted immediately following the line being split deleting text most text editors provide both delete and rub-out operation for removing individual characters from document these are typically mapped to the delete and backspace keysrespectively both operations delete character and shift all following characters on the same line forward one position the difference between
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 moves the cursor one position to the left when newline character is deletedthe current line and the one immediately following are merged the newline character at the end of the last line in the document cannot be deleted most text editors provide other text manipulation operations such as truncating line from the cursor position to the end of the line this operation typically does not remove the newline character at the end of the linebut instead simply deletes the non-newline characters from the cursor position to the end of the line some editors may also provide an operation to delete the entire line on which the cursor is positioned the edit buffer adt we are now ready to define an edit buffer adt that can be used with simple text editor our definition is based on the description of text editors presented in the previous section in order to keep the example simplewe limit the operations available with our adt define editbuffer adt an edit buffer is text buffer that can be used with text editor for storing and manipulating the text as it is being edited the buffer stores plain text with no special formatting or markup codesother than the common ascii special characters like tabs and newlines individual lines are terminated with newline character the current cursor position is maintained and all operations are performed relative to this position the cursor can only be positioned where character currently exists the cursor can never be moved outside the bounds of the document the buffer can insert characters in either insert or overwrite entry mode editbuffer()creates new and empty edit buffer an empty buffer always contains single blank line and the cursor is placed at the first position of this blank line the entry mode is set to insert numlines()returns the number of lines in the text buffer numchars()returns the length of the current line that includes the newline character lineindex()returns the line index of the line containing the cursor the first line has an index of columnindex()returns the column index of the cursor within the current line the first position in each line has an index of
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()returns the character at the current cursor position getline()returns the contents of the current line as string that includes the newline character moveupnum )moves the cursor up num lines the cursor is kept at the same character position unless the new line is shorterin which case the cursor is placed at the end of the new line the num is negativeand the cursor position is not changed movedownnum )the same as moveup(except the cursor is moved down movedochome()moves the cursor to the document' home positionwhich is the first line and first character position in that line movedocend()moves the cursor to the document' end positionwhich is the last line and first character position in that line moveleft()moves the cursor to the left one position the cursor is wrapped to the end of the previous line if it is currently at the front of line moveright()moves the cursor to the right one position the cursor is wrapped to the beginning of the next line if it is currently positioned at the end of line movelinehome()moves the cursor to the front of the current line at the first character position movelineend()moves the cursor to the end of the current line breakline()starts new line at the cursor position newline character is inserted at the current position and all characters following are moved to new line the new line is inserted immediately following the current line and the cursor is adjusted to be at the first position of the new line deleteline()removes the entire line containing the cursor the cursor is then moved to the front of the next line if the line being deleted is the last linethe cursor is moved to the front of the previous line truncateline()removes all of the characters at the end of the current line starting at the cursor position the newline character is not removed and the cursor is left at the end of the current line
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 newline character and the entry mode is overwritethe new character is inserted at the end of the line the cursor is advanced one position if char is the newline characterthen line break occurswhich is the same as calling breakline(deletechar()removes the character at the current position and leaves the cursor at the same position ruboutchar()removes the character preceding the current position and moves the cursor left one position if the cursor is currently at the front of the linethe newline character on the preceding line is removed and the current line and the preceding line are merged into single line deleteall()deletes the entire contents of the buffer and resets it to the same state as in the constructor the definition of the adt includes the operations sufficient for use with simple text editor all of the information needed by an editor to display or manipulate the text is available through the defined operations implementation many different data structures can be used to implement the edit buffer adt the choice can depend on the type of editor with which the buffer will be used for examplewhen editing field within dialog box or web pagethe editing capabilities and the buffer size are usually limited but full-blown text edit like jedit or notepad requires dynamic bufferwhich can grow and shrink in size for our implementationwe are going to use doubly linked list of python listswhich provides dynamic capabilities in terms of growing and shrinking the buffer as needed while providing quick line insertions and deletions the individual lines of text will be stored in the nodes of the doubly linked list while the individual characters within the lines will be stored in python lists figure illustrates sample buffer using this organization the use of linked list provides fast line insertions and deletions as text is added and removed the doubly linked version allows for quick movement within the buffer both forward and backward as the user navigates among the lines of text the choice of the vector to store the individual characters allows for quick modifications as characters are added and deleted existing characters can be directly modified or deleted and new characters inserted without the overhead required when using strings although the python list does require resizingit' typical for individual lines of text on average to be relatively short
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 implementation of some operations and helper methodsmany of which can be implemented in similar fashion to those providedare left as exercises several of the operations simply provide status information and are straightforward in their implementation these are provided in the listing without commentary others are more involved and require brief discussionwhich is provided the following sections listing the editbuffer py module implements the edit buffer adt using doubly linked list of vectors class editbuffer constructs an edit buffer containing one empty line of text def __init__self )self _firstline _editbuffernode['\ 'self _lastline self _firstline self _curline self _firstline self _curlinendx self _curcolndx self _numlines self _insertmode true returns the number of lines in the buffer def numlinesself )return self _numlines (listing continued
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 )return self _curcolndx sets the entry mode based on the boolean value insert def setentrymodeselfinsert )self _insertmode insert toggles the entry mode between insert and overwrite def toggleentrymodeself )self _insertmode not self _insertmode returns true if the current entry mode is insert def ininsertmodeself )return self _insertmode =true returns the character at the current cursor position def getcharself )return self _curline textself _curcolndx returns the current line as string def getlineself )linestr "for char in self _curline text linestr char return linestr moves the cursor up num lines def moveupselfnlines )if nlines < return elif self _curlinendx nlines nlines _curlinendx for in rangenlines self _curline self _curline prev self _curlinendx -nlines if self _curcolndx >self numchars(self movelineend(moves the cursor left one position def moveleftself )if self _curcolndx = if self _currowndx
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 the cursor position nlcontents self _curline text[self _curcolndx:insert newline character and truncate the line del self _curline text[self __curcolndx:self _curline text append'\ninsert the new line and increment the line counter self _insertnodeself _curlinenlcontents move the cursor self _curline newline self _curlinendx + self _curcolndx inserts the given character at the current cursor position def addcharselfchar )if char ='\nself breakline(else ndx self _curcolndx if self ininsertmode(self _curline text insertndxchar else if self getchar(='\nself _curline text insertndxchar else self _curline textndx char self _curcolndx + removes the character preceding the cursorcursor remains fixed def deletecharself )if self getchar(!'\nself _curline text popself _curcolndx else if self _curline is self _lastline return else nextline self _curline next self _curline text pop(self _curline text extendnextline text self _removenodenextline (listing continued
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 pointers for the doubly linked list the number of lines in the buffer is maintained using numlines and the current entry mode is specified by the boolean insertmode the current cursor position within the buffer must be trackedwhich is done using curline and curcolndx the former is linked list external reference since it points to node in the doubly linked list and the latter is an index value referencing position within the vector for the current line the line number on which the cursor is currently positioned is also maintained since it will be needed by the getline(method the adt definition calls for newly created buffer to be initially set to empty while an empty buffer contains no visible charactersit will contain single blank line that consists of lone newline character node is created and initialized with vector containing single newline character the nodes in the doubly linked list will be instances of the editbuffernode classthe definition of which is provided in lines - the cursor is initially placed at the home positionwhich in an empty document corresponds to the newline character in the newly created blank line finallythe initial entry mode is set to insert mode cursor movement number of operations in the edit buffer adt handle movement of the cursorwhich allows for character manipulation at different points in the buffer these routines modify the current cursor position by appropriately adjusting the curlinecurlinendxand curcolndx fields vertical movement of the cursor is handled by four methodsmovedochome()movedocend()movedown()and moveup(the cursor can be moved up or down one line or multiple lines at time but it can never be moved outside the valid range implementation of the moveup(method is provided in lines - of listing by definitionthe number of lines the cursor is to be moved must be positiveotherwise the cursor is not moved in additionthe cursor cannot be moved further up than the first line in the document these conditions are evaluated by the first two logical expressions if nlines would result in the cursor being moved beyond the first linenlines has to be adjusted to limit the movement to the first line nexta for loop is used to move the curline reference up the indicated number of
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 managed by four methodsmoveleft()moveright()movelinehome()and movelineend(moving the cursor to the beginning or end of line simply requires modifying the value of curcolndx moving the cursor horizontally one space can be as simple as adjusting curcolndx by oneexcept when the cursor is at the beginning or ending of the line when moving left or rightrespectively implementation of the moveleft(method is provided in lines - when moving left one space and the cursor is at the beginning of the linethe cursor must be moved to the end of the previous line this can be accomplished by moving the cursor up one line and then to the end of that line of course this is only done if the current line is not the first line in the buffer moving right one space can be implemented in similar fashion the implementation of the remaining cursor movement methods is left as an exercise modifying the buffer moving the cursor is somewhat easier than modifying the contents of the buffer most modifications must consider the newline characterwhich may require splitting line or merging two lines depending on the specific operation we begin our look at buffer modifications with the operation of adding single character the action taken when adding character in the addchar(methodshown in lines - of listing depends on the entry mode and what character is being added in either modewhen adding newline characterthe result is the same as breaking line at the current position and thus this can be done with the breakline(method when the current entry mode is set to insertthe character is always inserted into the vector at the current cursor positionwhich causes the following characters on the same line to shift down one place when inserting character at the end of the linewe are actually inserting it immediately preceding the newline character thusthe newline character will always be the last character in the vector the action taken when adding character in overwrite mode depends on the position of the cursor when the cursor is at the end of linecharacters are inserted in the same fashion as if the entry mode was set to insert the newline character is never overwritten otherwisethe new character simply replaces the character at the cursor position after adding new characterthe cursor is always moved to the right one place this can be done by simply adding one to curcolndx since the cursor never moves to the next line during an add operation unless newline character is being added the latter case is handled by the breakline(method deleting character from the buffer is straightforward if the character is not the newline character it only requires removing or popping the character at the current cursor position within the vector containing the current line the implementation of the deletechar(method is provided in lines - of listing
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 firstthe newline character on the current line must be removed and the current line extended by appending to it the contents of the next line thenthe node and buffer entry for the next line must be removed from the doubly linked list this step is performed using the removenode(helper methodthe implementation of which is left as an exercise the helper method also handles the final step in merging the two lineswhich is to decrement the line count by one splitting line we conclude our discussion with the breakline(methodthe implementation of which is provided in lines - of listing this operation splits line into two lines at the current cursor position with the character at the cursor position becoming part of the new line figure illustrates the sample buffer after splitting the third line at the letter "iof the word "in curline (acurline (bfigure breaking line of text at the cursor position(athe sample buffer before the split and (bthe result after the split with the cursor position adjusted
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 method to then insert new line into the buffer the helper method inserts new node following the one pointed to by curline and containing the supplied contents the last step required in breaking the current line is to move the cursor to the front of the new line exercises evaluate the four basic linked list operations for sorted doubly linked list and indicate the worst case time-complexities of each evaluate the worst case time-complexity for the search operation on doubly linked list using probe pointer evaluate the worst case time-complexity of the sparse matrix adt implemented in programming project provide the code to implement the four basic operations -traversalsearchinsertiondeletion -for an unsorted doubly linked list provide the code to delete node from sorted doubly linked list provide the code to delete node from sorted singly linked circular list programming projects complete the implementation of the editbuffer class from section modify the moveleft(and moveright(methods to accept an integer to indicate the number of spaces to move in the respective direction modify the editbuffer class to include the following operationsgetpagefirstlast )returns vector of strings consisting of the rows [first last]which can be used for displaying page of text insertstringstr )inserts string of text within the current line starting at the current cursor position movetolinendxcolndx )moves the cursor to the indicated position within the buffer if linendx is out of rangeno action is taken if colndx is larger than the current linethen the cursor is positioned at the end of that line
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 the given search string modify the editbuffer class to include the following file / operations for saving and loading the buffersavefilename )saves the text in the buffer to the text file filename loadfilename )loads the text file named filename into the buffer if the buffer is not emptythe original contents are deleted before the file is loaded the given filename must refer to an existing and valid text file create line editor application that uses the editbuffer class and allows user to edit text document in the old "line editingstyle define and implement multichain adt for storing and accessing student records as described in section implement the sparse matrix adt using the multi-linked lists as described in section consider the vector adt from programming project (aprovide new implementation that uses doubly linked list and probe reference for locating specific element (bevaluate your new implementation to determine the worst case run time of each operation (cwhat are the advantages and disadvantages of using doubly linked list to implement the vector adtcompare this implementation to that of using singly linked list consider the map adt from section (aprovide new implementation that uses sorted doubly linked list and includes probe reference for the search operations (bmodify your map class to include an iterator for use with for loop multimap adt is similar to the map adt but it uses two keys that map to single data item instead of single key as used with the map adt define and implement multimap adt
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 advanced backtracking problems while recursion is very powerfulrecursive solutions are not always the most efficient in some instanceshoweverrecursion is the implementation of choice as it allows us to easily develop solution for complicated problem that may otherwise be difficult to solve recursive functions function (or methodcan call any other function (or method)including itself function that calls itself is known as recursive function the result is virtual loop or repetition used in fashion similar to while loop consider the simple problem of printing the integer values from to in reverse order the iterative solution for this problem is rather simple when using loop construct but it can also be solved recursivelythat isusing recursive function suppose we have implemented the following recursive functiondef printrevn )if printn printreversen- and we call the function with an argument of printrev
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 the printrev( function callthe sequential flow is once again interrupted as control is transferred to another instance of the printrev(function the body of this instance begins execution at the first statementbut this time with figure (aillustrates the execution of the recursive function as group of boxes with each box representing single invocation of the printrev(function the boxes contain the contents of local variables and only the statements of the function actually executed each recursive call to printrev(is shown inside its own box with the boxes positioned at the point where the function was invoked printrev )nprintinc ) if printincn if printn printrevn printrev )printinc )nif printn printrevn if printincn printinc ) if printincn printrev ) if printn printrevn printinc ) if printincn printinc )nif printrev ) if printn printrevn printrev )nif printn printn printn printn ( (bfigure recursive flow of execution(aprintrev(and (bprintinc(these recursive calls continue until value of zero is passed to the functionat which time the body of the if statement is skipped and execution reaches the end of the function as with any function callwhen execution reaches the end of the function or the return statement is encounteredexecution returns to the location where the function was originally called in this casethe call to printrev(
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 printrev( instance thusexecution returns to the first statement after that invocation after execution returns to the printrev( instancethe end of that function is reached and again execution is returned to the location where that instance was invoked the result is chain of recursive returns or recursive unwinding back to the original printrev( function call what changes would be needed to create recursive function to print the same integer values in increasing order instead of reverse orderwe can change the location of the recursive call to change the behavior of the recursive solution consider new recursive print functiondef printincn )if printincn- printn in this versionthe recursive call is made before the value of is printed the result is series of recursive calls before any other action is performed the actual printing of the values is performed after each instance of the function returnsas illustrated in figure ( properties of recursion all recursive solutions must satisfy three rules or properties recursive solution must contain base case recursive solution must contain recursive case recursive solution must make progress toward the base case recursive solution subdivides problem into smaller versions of itself for problem to be subdividedit typically must consist of data set or term that can be divided into smaller sets or smaller term this subdivision is handled by the recursive case when the function calls itself in the printrev(functionthe recursive case is performed for all values of the base case is the terminating case and represents the smallest subdivision of the problem it signals the end of the virtual loop or recursive calls in printrev()the base case occurred when and the function simply returned without performing any additional operations finallya recursive solution must make progress toward the base case or the recursion will never stop resulting in an infinite virtual loop this progression
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 current value of in each recursive function call factorials the factorial of positive integer can be used to calculate the number of permutations of elements the function is defined asnn ( ( with the special case of this problem can be solved easily using an iterative implementation that loops through the individual values [ nand computes product of those values but it can also be solved with recursive solution and provides simple example of recursion consider the factorial function on different integer values after careful inspection of these equationsit becomes obvious each of the successive equationsfor can be rewritten in terms of the previous equation ( ) ( ) ( ) ( ) ( )since the function is defined in terms of itself and contains base casea recursive definition can be produced for the factorial function as shown here listing provides recursive implementation of the factorial function if nn ( )!if
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 illustrated the different results that were achieved depending on the location of the recursive call within the function this type of illustration can be very helpful to visualize the flow of execution within and between various functionsbut it' not as useful in developing and understanding recursive functions when developing or evaluating recursive functionwe typically use recursive call tree such as the one for the factorial function illustrated in figure the diagram consists of small boxes and directed edges between the boxes each box represents function call and is labeled with the name of the function and the actual arguments passed to the function when it was invoked the directed edges between the boxes indicate the flow of execution the solid edges indicate the function from which call originated for examplein figure we see the call to fact( was made from the main(function while the call to fact( was made during the execution of fact( the dashed edges indicate function returns and are labeled with the return value if value is returned to the caller main( fact( fact( fact( fact( fact( figure recursive call tree for fact(
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 shown in figure sample program containing three functions def main() foo bar def foox )if ! return else return foox- def barn )if printn barn- main(since the main routine makes two function callsboth are indicated as directed edges originating from the main(box you will also notice the foo(function makes recursive call to itselfbut the second call is not indicated in the call tree the reason is during this execution of the programwith the given arguments to foo()the logical condition in the if statement evaluates to true andthusthe recursive call is never made the call tree only shows the functions actually called during single executionwhich is based on given set of dataa specific function argument valueor specific user input to follow the flow of execution in figure we start with the top boxthe one to which no solid directed edges flow into in this casethat box is the main(function from the main routinewe take the path along the leftmost solid edge main(foo( bar( print( bar( print( bar( figure sample call tree with multiple calls from each function
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 eventually return to the main(routine box with no further edges to follow at that pointexecution terminates the fibonacci sequence the fibonacci sequence is sequence of integer values in which the first two values are both and each subsequent value is the sum of the two previous values the first terms of the sequence are the nth fibonacci number can be computed by the recurrence relation (for ) ib(nf ib( ib( )if nif or recursive function for the computing the nth fibonacci number is shown in listing this function illustrates the use of multiple recursive calls from within the body of the function the call tree corresponding to the function call fib( is illustrated in figure listing the fib(recursive function compute the nth number in the fibonacci sequence def fibn )assert > "fibonacci not defined for if = return else return fib( fib( how recursion works when function is calledthe sequential flow of execution is interrupted and execution jumps to the body of that function when the function terminatesexecution returns to the point where it was interrupted before the function was invoked but how does it know where to returnwe know for sureit' not magic
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 address this is the location of the next instruction to be executed when the function terminates thuswhen function returnsthe address is obtained from the activation record and the flow execution can return to where it left off before the function was called the activation records also include storage space for the allocation of local variables remembera variable created within function is local to that function and is said to have local scope local variables are created when function begins execution and are destroyed when the function terminates the lifetime of local variable is the duration of the function in which it was created an activation record is created per function callnot on per function basis when function is calledan activation record is created for that call and when it terminates the activation record is destroyed the system must manage the collection of activation records and remember the order in which they were created the latter is necessary to allow the system to backtrack or return to the next statement in the previous function when an invoked function terminates it does this by storing the activation records on run time stack the run time stack is just like the stack structure presented in but it' hidden from the programmer and is automatically maintained consider the execution of the following code segmentwhich uses the factorial function defined earlierdef main() fact main(
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 fact( )return to main(nmain()return address ypush push record main()return address yrecord ( (bfigure the initial run time stack for the sample code segment the factorial function is recursively called until the base case is reached with value of at this pointthe run time stack contains four activation recordsas illustrated figure (awhen the base case statement at line of listing is executedthe activation record for the function call fact( is popped from the stackas illustrated in figure ( )and execution returns to the function instance fact( this process continues until all of the activation records have been popped from the stack and the program terminates fact( )return to fact( fact( )return to fact( npop record fact( )return to fact( fact( )return to main(nfact( turn to re fact( fact( )return to main( main()return address main()return address ( (bfigure the run time stack for the sample program when the base case is reached
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 singly linked list such as the one shown in figure head figure sample singly linked list since the links are in one directionwe cannot easily access the nodes in reverse order brute-force approach to solving this problem would be to use nested loops to iterate over the linked list multiple times with each iteration of the inner loop ending one node shorter than previous iteration this approach is implemented by the function in listing but it has run time of ( listing brute-force approach for printing singly linked list in reverse order print the contents of singly linked list in reverse order def printlistbfhead )count the number of nodes in the list numnodes curnode head while curnode is not none curnode curnode next numnodes + iterate over the linked list multiple times the first iteration prints the last itemthe second iteration prints the next to last itemand so on for in rangenumnodes )the temporary pointer starts from the first node each time curnode head iterate one less time for iteration of the outer loop for in rangenumnodes )curnode curnode next print the data in the node referenced by curnode printcurnode data
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 iteration over the list and before the items are popped is shown in figure assuming the use of the linked list version of the stackprintliststack(has run time of ( )the proof of which is left as an exercise listing using stack to print linked list in reverse order print the contents of linked list in reverse order using stack from lliststack import stack def printliststackhead )create stack to store the items stack(iterate through the list and push each item onto the stack curnode head while curnode is not none pushcurnode data curnode curnode next repeatedly pop the items from the stack and print them until the stack is empty while not isempty(item pop(print item recursive solution for this problem is also possible to design the solutionwe use the divide and conquer strategy introduced in with this strategyyou solve the larger problem by dividing it into smaller problems of itself and solving the smaller parts individually linked list is by definition recursive structure that isthe list can be thought of as node linked to sublist of nodes figure the resulting stack after iterating over the linked list from figure
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 the contents of the node itself head (ahead (bfigure abstract view of the linked list as node linked to sublist of nodes the solution subdivides the problem into smaller parts of itself and contains recursive case but what about the base casewhich ends the subdivision and in turn stops the recursive callsthe recursion should stop when the next sublist is emptywhich occurs when the link field of the last node is null simple and elegant python implementation for the recursive solution is provided in listing listing the printlist(recursive function print the contents of linked list using recursion def printlistnode )if node is not none printlistnode next printnode data to help visualize how the printlist(function worksthe call stack and the linked list are illustrated in figure it assumes the main routine is defined as followsdef main()head buildlinkedlist(printlisthead
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 more activation records are pushed onto the run time stackthe corresponding node argument is assigned to point to the next node in the list when the base case is reachedthe node argument of each of the preceding function calls will point to different node in the list thusas the recursion unwindsthe contents of each node can be printedresulting in listing of the values in reverse order both the printliststack(and printlist(functions provide an implementation to the problem of printing linked list in reverse order the former requires the use of an explicit loop for iterating through the list and stack to store the data for later printing in the recursive version the loop and stack are implicit the loop is replaced by the recursive calls while the user-specified stack is replaced by the run time stack on which activation records are pushed for each call to the function tail recursion sometimes an algorithm is easy to visualize as recursive operationbut when implemented as recursive functionthe solution proves to be inefficient in these casesit can be beneficial to use non-recursive implementation that makes use of basic iterative loop or the software stack adt from the main reason for using recursion is to push values onto the run time stack that need to be saved until the recursive operation used to solve the smaller sub
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 onto the run time stack as part of the activation record each time the function was called now suppose we implement recursive function to print the items of linked list in order from beginning to end instead of using simple loop structuredef printinordernode )if node is not none printnode data printinordernode next this function eliminates the need for loop to iterate through the listbut do we have anything to save on the stack until the recursive call returnsthe answer is no when the recursive call returnsthe function is finished and it simply returns this is an example of tail recursionwhich occurs when function includes single recursive call as the last statement of the function in this casea stack is not needed to store values to be used upon the return of the recursive call and thus solution can be implemented using an iterative loop instead recursive applications there are many applications that can be solved using recursion some in factcan only be solved using recursion in this sectionwe introduce some of the classic problems that require the use of recursion or can benefit from recursive solution recursive binary search the binary search algorithmwhich we introduced in improves the search time required to locate an item in sorted sequence we provided an iterative implementation of the binary search algorithm in but the algorithm can also be implemented recursively since it can be expressed in smaller versions of itself in searching for target within the sorted sequencethe middle value is examined to determine if it is the target if notthe sequence is split in half and either the lower half or the upper half of the sequence is examined depending on the logical ordering of the target value in relation to the middle item in examining the smaller sequencethe same process is repeated until either the target value is found or there are no additional values to be examined recursive implementation of the binary search algorithm is provided in listing as with the earlier versionthis version also works with virtual subsequences instead of physically splitting the original sequence the two argumentsfirst and lastindicate the range of elements within the current virtual subsequence on the first call to the functionthese values are set to the full range of the original sequence
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 element at the midpoint contain the targetif theseq[mid=target return true base case # or does the target precede the element at the midpointelif target theseq[midreturn recbinarysearchtargettheseqfirstmid or does it follow the element at the midpointelse return recbinarysearchtargettheseqmid last we evaluated the binary search algorithm in and found it required (log ntime in the worst case to determine the run time of recursive implementationwe must consider the time required to execute single invocation of the function and the number of times the function is called in evaluating the time of single function invocationwe use the same technique as we applied in previous and sum the times of the individual statements the recursive callshoweverare not included since their times will be computed separately for the recbinarysearch(functionwe can quickly determine that each non-recursive function call statement only requires ( time to help determine the number of times the recursive function is calledwe can use its recursive call tree consider the recursive call tree for the binary search algorithmas shown at the top of figure which results when searching for value in the sequence shown at the bottom of the figure the number of function call boxes in the tree for given sequence of length will indicate the total number of times the function is called there are two recursive calls to recbinarysearch(within the function bodybut only one will be executed for each invocation thusthere will be single function call box at each level in the call tree and we only have to determine how many levels there are in the call tree when searching sequence of items the worst case occurs when the target value is not in the sequencewhich can be determined when the first and last markers cross each other with first last as with the iterative version of the algorithmthe number of elements in the sorted sequence that must be searched is reduced by half each time the function is called we know from that repeatedly reducing the input size by half requires log reductions in order to reach the case where there are no additional elements to be searched thusthe recursive version of the binary search requires (log ntime in the worst case
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 of hanoi puzzleinvented by the french mathematician edouard lucas in consists of board with three vertical poles and stack of disks the diameter of the disks increases as we progress from the top to bottomcreating tower structure the illustration in figure shows the boardthe three towersand five disks any number of disks can be used with the puzzlebut we use five for ease of illustration pole pole pole figure the towers of hanoi puzzle with five disks the objective is to move all of the disks from the starting pole to one of the other two poles to create new tower there arehowevertwo restrictions( only one disk can be moved at timeand ( larger disk can never be placed on top of smaller disk
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 thinking about the easiest stepmoving the top disklet' start with the hardest step of moving the bottom disk suppose we already know how to move the top four disks from pole to pole bresulting in the board shown in figure moving the disk from pole to pole is now rather easy since it' the only disk left on pole and there are no disks on pole after moving the largest diskwe then move the other four disks from pole to pole pole pole pole figure the towers of hanoi puzzle with four disks moved to pole of coursewe still have to figure out how to move the top four disks there is no reason we cannot use the same technique to move the top four disks and in fact we must use the same techniquewhich leads to recursive solution given disks and three poles labeled source ( )destination ( )and intermediate ( )we can define the recursive operation asmove the top disks from pole to pole using pole move the remaining disk from pole to pole move the disks from pole to pole using pole the first and last steps are recursive calls to the same operation but using different poles as the sourcedestinationand intermediate designations the base casewhich is implicit in this descriptionoccurs when there is single disk to moverequiring that we skip the first and last step finallythe solution makes progress toward the base case since the recursive calls move one less disk than the current invocation eventuallywe will end up with single disk to move the high-level solution given above for solving the towers of hanoi puzzle can be easily converted to python functionas shown in listing for the second step of the process where we actually move diskwe simply print message indicating which disk was moved and the two poles it was moved between
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 function callmove the output produced from the execution is shown here while the first four moves of the disks are illustrated graphically in figure move - move - move - move - move - move - move - to evaluate the time-complexity of the move(functionwe need to determine the cost of each invocation and the number of times the function is called for any value of each function invocation only requires ( time since there are only two non-recursive function call steps performed by the functionboth of which require constant time nextwe need to determine how many times the function is called consider the recursive call tree in figure which results from the function invocation move( the first invocation of move(results in two recursive callsboth of which move disks both of these invocations each make two recursive calls to move disks those four invocations each make two recursive calls to move disks and so on until there is single disk to be moved to determine the total number of times the function is calledwe need to calculate the number of times the function executes at each level of the call tree and then sum those values to obtain the final result the number of function calls at each level is double the number of calls at the previous level if we label each level of the call tree starting with at the top and going down to at the bottomthen the number of function calls at each level is equal to summing the number of calls at each level results in the summation - - = or total of function calls thusthe recursive solution for solving the towers of hanoi problem requires exponential time of ( in the worst case
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 such as computing fibonacci number those were introduced to provide simple examples of recursion other problems such as solving the towers of hanoi puzzle can only be done using recursive algorithm there are some problemshoweverin which the recursive version is more efficient than the iterative version one such example is the exponential operationwhich raises number to power by definitionthe exponential operation xn can be expressed as multiplied by itself times ( xfor exampley would be computed as of coursein python this can be done using the exponential operatory * but how is this operation actually performed in pythona basic implementation would use an iterative loopdef exp xn ) for in rangen ) * return this implementation requires linear timewhich is relatively slow if we are raising value to large power for examplesuppose we want to compute the basic implementation requires , iterations to compute this valuebut each iteration performs multiplicationwhich itself is time consuming when compared to other operations fortunatelythere is faster way to raise value to an integer
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 / ( xif is odd listing provides recursive function for raising to the integer value of since two of the expressions compute ( ) / we go ahead and compute this value as the result on line and then determine if is even or odd if is eventhen the result is returnedotherwisewe have to first multiply the result by to include the odd factor the run time analysis of exp(is left as an exercise listing the recursive implementation of exp( recursive implementation for computing * where is an integer def expxn )if = return result expx xn / if = return result else return result playing tic-tac-toe in this technological ageit' very likely you have played computer game in which you are competing against the computer for exampleyou may have played the game of checkerschessor something as simple as tic-tac-toe in any such gamewhen it' the computer' turn to playthe computer must make decision as to what play to make depending on the game and your level of expertiseyou may sometimes think the computer is genius or that there is some kind of magic going on behind the scenes sohow does the computer make its decisionone simple technique the game programmer can apply is the use of game tree game tree provides the sequence of all possible moves that can be made in the game for both the computer and the human opponent when the computer has to make moveit can evaluate the game tree and determine its best move the best move in this case is one that allows the computer to win before its human opponent in the fewest possible moves thuswhen playing against computerit' not that the computer is highly intelligentbut that the computer can evaluate every possible move from the current point to the end of the game and choose the best move humans simply
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 os in the squares one player is assigned the xs while the other is assigned the os play continues until all of the squares are filledresulting in drawor one of the players wins by aligning three identical pieces verticallydiagonallyor horizontally the following diagrams show three different game boardstwo resulting in wins and one resulting in drawo suppose you are playing game of tic-tac-toe in which four moves have been played as followso and now it' ' turn to playwhich happens to be the computer the computer needs to evaluate all of its possible moves to determine the best move to makewhich it can do by evaluating the game tree starting from this point in the game it can use recursion and build recursive call tree to represent all possible moves in the game for both itself and its opponent during the recursionthe tokens are placed on the board for both the computer and its opponent as if they were both actually playing as the recursion unwindsthe tokens are picked to return the game to its current state this game tree shows the five possible moves the computer can make at this pointo
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 evaluating this portion of the treethe computer would soon learn it could win in two additional moves if its opponent placed their token in the uppermiddle square following the middle branch from the topthe computer would learn that if its opponent placed their token in the middle-right square insteadit could not win in two more moves but the opponent could win in three moves in this situation finallyit would be determined that the opponent could win in the next move by playing in the lower-left square if the computer made this play while that' badthis is only one possible move the computer could make it still has to evaluate the other possible moves to determine if one is better eventuallythe computer would determine that the best move would be to play in the lower-left square this would be based on the fact it could win on the next move by playing in either of two different places before its opponent could win using recursion to build game tree can make for very interesting games in which human competes against the computer we leave as an exercise the implementation of function to find the best move for the computer in playing tic-tac-toe applicationthe eight-queens problem in we explored the concept of backtracking and its use in solving certain problems such as that of finding path through maze in that problemwe saw that backtracking allows us to move forward searching for solution andwhen necessaryto back up one or more steps in order to try other options backtracking solutions require the use of stack in order to remember the current solution and to remove the latter parts of that solution when it' necessary to back up and try other options
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 problem the task is to place eight queens onto chessboard such that no queen can attack another queen in the game of chessa square board is used consisting of squares arranged in eight rows of eight columns each player has collection of playing pieces that move and attack in fixed ways the queen can move and attack any playing piece of the opponent by moving any number of spaces horizontallyverticallyor diagonallyas illustrated in figure figure legal moves of the queen in the game of chess for the eight-queens problemwe use standard chessboard and eight queens the objective is to place the eight queens onto the chessboard in such way that each queen is safe from attack by the other queens there are solutions to this problemtwo of which are shown in figure figure two solutions for the eight-queens problem
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 but when attempting to solve the original eight-queens problemthis approach may lead to chaos consider more organized approach to solving this problem since no two queens can occupy the same columnwe can proceed one column at time and attempt to position queen in each column we start by placing queen in the upper-left square or position ( using the - array notationwith this movewe now eliminate all squares horizontallyverticallyand diagonally from this position for the placement of additional queens since these positions are guarded by the queen we just placed with the first queen placed in the first columnwe now move to the second column the first open position in this column where queen can be placed without being attacked by the first queen we placed is at position ( we can place queen in this position and mark those squares that this queen guardsremoving yet more positions for the placement of additional queens we are now ready to position queen in the third column but you may notice there are no open positions in the third column thusthe placement of the first two queens will not result in valid solution at this pointyou may be tempted to remove all of the existing queens and start over but that would be drastic move insteadwe can employ the backtracking strategy as introduced in in
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 squares that queen was guarding we then place the queen at the next available square within the same column ( and mark the appropriate squares guarded from this positionas shown herex now we can return to the third column and try again this timewe place queen at position ( )but this results in no open squares in the fourth column we could try other squares in the same columnbut none are open thuswe must pick up the queen from the third column and again backtrack to try other combinations we return to the second column and pick up the queen we placed earlier at position ( so we can try other squares within this column but there are no more open squares in the second column to tryso we must back up even furtherreturning to the first column when returning to columnthe first step is always to pick up the queen previously placed in that column
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 four-queens problemwe can use the same approach to solve the eight-queens problem the only difference between the two is that there is likely to be more backtracking required to find solution in additionwhile the four-queens problem has two solutionsthe eight-queens problem has solutions the original problem definition only considered finding solution for normal chessboard more general problemhoweveris known as the -queens problemwhich allows for the placement of queens on board of size where the same backtracking technique described earlier can be used with the -queens problemalthough finding solution to larger-sized boards can be quite time consuming we leave the analysis of the time-complexity as an exercise designing solution given the description of the eight-queens problem and the high-level overview of how to find solution to the four-queens problemwe now consider an implementation for solving this classic example of recursion and backtracking the board definition the implementation will consist of two partsa game board for placing the queens and recursive function for finding solution we begin with the definition of the nqueens board adt to represent the board and the placement of the queens
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 board numqueens()returns the number of queens currently positioned on the board unguardedrowcol )returns boolean value indicating if the given square is currently unguarded placequeenrow,col )places queen on the board at position (rowcolremovequeenrow,col )removes the queen from position (rowcolreset()resets the board to its original state by removing all queens currently placed on the board draw()prints the board in readable format using characters to represent the squares containing the queens and the empty squares using the adt given the adt definitionwe can now design recursive function for solving the -queens problem the function in listing takes an instance of the nqueens board adt and the current column in which we are attempting to place queen when called for the first timean index value of should be passed to the function the function begins by testing if solution has been found that is one of three base cases if no solution has been foundthen we must loop through the rows in the current column to find an unguarded square if one is founda queen is placed at that position (line and recursive call is made in an attempt to place queen in the next column upon return of the recursive callwe must check to see if solution was found with the queen placed in the square at position (row,colif solution was foundanother base case is reached and the function returns true if no solution was foundthen the queen in the current column must be picked up (line and another attempt made to place the queen within this column if all unguarded squares within the current column have been exhaustedthen there is no solution to the problem using the configuration of the queens from the previous columns in this casewhich represents the last base casewe must backtrack and allow the previous instance of the recursive function to try other squares within the previous column
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 that square board placequeenrowcol continue placing queens in the following columns if board solvenqueensboardcol+ we are finished if solution was found return true else no solution was found with the queen in this squareso it has to be removed from the board board removequeenrowcol if the loop terminatesno queen can be placed within this column return false implementing the adt having provided the recursive function for solving the -queens problemwe leave the implementation of the nqueens board adt as an exercise in this sectionhoweverwe discuss possible data structures for representing the actual board the most obvious choice is - array of size the elements of the array can contain boolean values with true indicating the placement of the queens to determine if given square is unguardedloops can be used to iterate over all of the squares to which queen can move from that position if queen is found in any of the squares searched during the loop iterationsthen we know the square is currently guarded by at least one queen the placement and removal of the queens is also quite easy to implement using the - array structure as an alternativewe can actually use - array consisting of elements consider the illustration in figure on the next pagewhich shows the abstract view of an board at the top and - array at the bottom used to represent the board each element of the - array corresponds to one column on the board the elements of the - array will contain row indices indicating the positions of the queens on the board since only one queen can be placed within given columnwe need only keep track of the row containing the queen in the column when determining if square is unguardedwe can iterate through the row and column indices for the preceding columns on the board from which the given square can be attacked by queen instead of searching for true value within the elements of - arraywe need only determine if the elements of the - array contain one of the row indices being examined consider the illustration in
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 is queen already positioned on the current row as is the case in this example if queen was not found on the current rowthen we would have to search diagonally to the upper left and to the lower left in these two caseswe search the squares indicated by the arrows and examine the row indices of each and compare them to the entries in the - array if any of the indices matchthen queen is currently guarding the position and it is not legal move figure determining if square is unguarded using - array
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 recursive implementation of the binary search algorithm from listing exhibit tail recursionif notwhy not determine the worst case run time of the recursive exponential function exp( determine the worst case run time of the backtracking solution for the -queens problem design and implement an iterative version of the factorial function design and implement recursive function for determining whether string is palindrome palindrome is string of characters that is the same as the string of characters in reverse design and implement recursive function for computing the greatest common divisor of two integer values design and implement program that prints pascal' triangle using recursive implementation of the binomial coefficients functiona(nrnr!( ) implement the nqueens board adt using the indicated data structure to represent the chess board ( - array ( - array
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 solutions for given value of modify the solvenqueens(function from listing to count the number of solutions for given value of instead of simply determining if solution exists test your program on the following values of (the number of solutions for the given board size is indicated in parentheses( ( ( ( ( ( ( ( ( ( ( ( implement new version of the maze solving program from to use recursion instead of software stack design and implement program to play tic-tac-toe against the computer using recursive function to build game tree for deciding the computer' next move the knight' tour problem is another chessboard puzzle in which the objective is to find sequence of moves by the knight in which it visits every square on the board exactly once the legal moves of knight are shown in the diagram to the right design and implement program that uses recursive backtrack ing algorithm to solve the knight' tour your program should extract from the user starting position for the knight and produce list of moves that solves the knight' tour the knapsack problem is classic problem in computer science you are given knapsack and collection of items of different weights and your job is to try to fit some combination of the items into the knapsack to obtain target weight all of the items do not have to fit in the knapsackbut the total weight cannot exceed the target weight for examplesuppose we want to fill the knapsack to maximum weight of pounds from collection of seven items where the weights of the seven items are and for small number of itemsit' rather easy to solve this problem one such solutionfor examplewould be to include the items that have weights and but what if we had several thousand items of varying weights and need to fit them within large knapsackdesign and implement recursive algorithm for solving this problem
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 and removing existing items given the importance of searchingwe need to be able to accomplish this operation fast and efficiently if the collection is stored in sequencewe can use linear search to locate an item the linear search is simple to implement but not very efficient as it requires (ntime in the worst case we saw that the search time could be improved using the binary search algorithm as it only requires (log ntime in the worst case but the binary search can only be applied to sequence in which the keys are in sorted order the question becomescan we improve the search operation to achieve better than (log ntimethe linear and binary search algorithms are both comparisonbased searches that isin order to locate an itemthe target search key has to be compared against the other keys in the collection unfortunatelyit can be shown that (log nis the best we can achieve for comparison-based search to improve on this timewe would have to use technique other than comparing the target key against other keys in the collection in this we explore the use of non-comparison-based algorithm to provide more efficient search operation this is the same technique used in the implementation of python' dictionary structure introduction suppose you have collection of products for which you need to maintain information and allow for numerous searches on that information at the present timeyou only have small collection of products but you can envision having up to
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 contents of the array for collection of nine product codes depending on the number of searcheswe can choose whether to perform simple linear search on the array or first sort the keys and then use binary search even though this example uses small collectionin either case the searches still require at least logarithmic time and possibly even linear time in the worst case figure collection of product codes stored in an array given the small range of key valuesthis problem is special case the searches can actually be performed in constant time instead of creating an array that is only large enough to hold the products on handsuppose we create an array with elementsthe size needed to store all possible product codes we can then assign each key specific element in the array if the product code existsthe key and its associated data will be stored in its assigned element otherwisethe element will be set to none to flag the absence of that product the search operation is reduced to simply examining the array element associated with given search key to determine if it contains valid key or null reference to determine the element assigned to given keywe note that the product codes are in the range [ while the array indices are in the range [ there is natural mapping between the two key can be assigned to element key to element key to element and so on this mapping can be computed easily by subtracting from the key value or with the use of the modulus operator (key figure illustrates the storage of our sample product collection using this approach this technique provides direct access to the search keys when searching for keywe apply the same mapping operation to determine the array element that contains the given target for examplesuppose we want to search for product we compute to determine the key will be in element if it exists since search keys throughout the textwe have focused on the storage and use of search keys when discussing the search problem but rememberthe search keys are commonly associated with data record and are used as the unique identifier for that record while our examples have only illustrated the keyswe assume the associated data is also stored along with the search key note
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 we can directly examine specific element of the array and not have to compare the target key against the other keys in the collection hashing we can use the direct access technique for small sets of keys that are composed of consecutive integer values but what if the key can be any integer valueeven with small collection of keyswe cannot create an array large enough to store all possible integer values that' where hashing comes into play hashing is the process of mapping search key to limited range of array indices with the goal of providing direct access to the keys the keys are stored in an array called hash table and hash function is associated with the table the function converts or maps the search keys to specific entries in the table for examplesuppose we have the following set of keys and hash tablet containing elements we can define simple hash function (*that maps the keys to entries in the hash tableh(keykey you will notice this is the same operation we used with the product codes in our earlier example dividing the integer key by the size of the table and taking the remainder ensures the value returned by the function will be within the valid range of indices for the given table to add keys to the hash tablewe apply the hash function to determine the entry in which the given key should be stored applying the hash function to key yields result of which indicates should be stored in element of the hash table likewiseif we apply the hash function to the next four keys in the listwe findh( = ( = ( = ( = all of which are unique index values figure illustrates the insertion of the first five keys into the hash table
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 attempt to add key to the hash table the hash function maps this key to entry but that entry already contains key as illustrated in figure the result is collisionwhich occurs when two or more keys map to the same hash location we mentioned earlier that the goal of hashing is to provide direct access to collection of search keys when the key value can be one of wide range of valuesit' impossible to provide unique entry for all possible key values figure collision occurs when adding key if two keys map to the same table entrywe must resolve the collision by probing the table to find another available slot the simplest approach is to use linear probewhich examines the table entries in sequential order starting with the first entry immediately following the original hash location for key value the linear probe finds slot availableso the key can be stored at that positionas illustrated in figure ( ( figure resolving collision for key requires adding the key to the next slot
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 collision has to be resolved just like any otherby probing to find another slot in the case of key the linear probe leads us to slot as illustrated in figure ( ( figure adding key to the hash table(aperforming linear probeand (bthe result after adding the key if the end of the array is reached during the probewe have to wrap around to the first entry and continue until either an available slot is found or all entries have been examined for exampleif we add key to the hash tablethe hash function maps the key to slot which contains key the linear probeas illustrated in figure requires wrapping around to the beginning of the array searching searching hash table for specific key is very similar to the add operation the target key is mapped to an initial slot in the table and then it is determined if that entry contains the key if the key is not at that locationthe same probe used to add the keys to the table must be used to locate the target in this casethe ( ( figure adding key to the hash table(aperforming linear probeand (bthe result after adding the key
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 searching the hash table(aa successful search for key and (ban unsuccessful search for key deletions we've seen how keys are added to the table with the use of the hash function and linear probe for resolving collisions but how are deletions handleddeleting from hash table is bit more complicated than an insertion search can be performed to locate the key in similar fashion as the basic search operation described earlier but after finding the keywe cannot simply remove it by setting the corresponding table entry to none suppose we remove key from our hash table and set the entry at element to none what happens if we then perform search for key the htsearch(function will return falseindicating the key is not in the tableeven though it' located at element the reason for the unsuccessful search is due to element containing null reference from that key having been previously removedas illustrated in figure rememberkey maps to element but when it was addeda new slot had to be found via probe since key already occupied that slot if we simply remove key there is no way to indicate we have to probe past this point when searching for other keys instead of simply setting the corresponding table entry to nonewe can use special flag to indicate the entry is now empty but it had been previously occupied figure incorrect deletion from the hash table
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 from the hash table clustering as more keys are added to the hash tablemore collisions are likely to occur since each collision requires linear probe to find the next available slotthe keys begin to form clusters as the clusters grow largerso too does the probability that the next key added to the table will result in collision if our table were emptythe probability of key being added to any of the empty slots is out of since it is equally likely the key can hash to any of the slots now consider the hash table in figure what is the probability the next key will occupy the empty slot at position if the next key hashes to this positionit can be stored directly into the slot without the need to probe this also results in probability of out of but the probability the next key will occupy slot is out of if the next key hashes to any of the slots between and it will be stored in slot due to the linear probe required to find the first position beyond the cluster of keys thusthe key is five times more likely to occupy slot than slot this type of clustering is known as primary clustering since it occurs near the original hash position as the clusters grow largerso too does the length of the search needed to find the next available slot we can reduce the amount of primary clustering by changing the technique used in the probing in this sectionwe examine several different probing techniques that can be employed to reduce primary clustering modified linear probe when probing to find the next available slota loop is used to iterate through the table entries the order in which the entries are visited form probe sequence the linear probe searches for the next available slot by stepping through the hash table entries in sequential order the next array slot in the probe sequence can be represented as an equationslot (home im
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 table of size ( = ( = ( = ( = ( = ( = ( = ( = = = = = = = when the keys are inserted in the order we can improve the linear probe by skipping over multiple elements instead of probing the immediate successor of each element this can be done by changing the step size in the probe equation to some fixed constant cslot (home cm suppose we use linear probe with to build the hash table using the same set of keys this results in only two collisions as compared to six when (the resulting hash table is illustrated in figure ) ( = ( = ( = ( = ( = ( = ( = ( = = = figure the hash table using linear probe with any value can be used for the constant factorbut to ensure the probe sequence includes all table entriesthe constant factor and the table size must be relatively prime with hash table of size the linear probe with constant factor will visit every element for exampleif the key hashes to position the table entries will be visited in the following order if we use value of the probe sequence will be
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 keys out from the initial hash positionbut it can still result in clustering the clusters simply move equal distance from the initial hash positions better approach for reducing primary clustering is with the use of quadratic probing which is specified by the equationslot (home quadratic probing eliminates primary clustering by increasing the distance between each probe in the sequence when used to build the hash table using the sample set of keyswe get seven collisions (the resulting hash table is illustrated in figure ) ( = ( = ( = ( = ( = ( = ( = ( = = = = = = = = while the number of collisions has increasedthe primary clustering has been reduced in practicequadratic probing typically reduces the number of collisions but introduces the problem of secondary clustering secondary clustering occurs when two keys map to the same table entry and have the same probe sequence for exampleif we were to add key to our tableit would hash to slot and follow the same probe sequence as key finallythere is no guarantee the quadratic probe will visit every entry in the table but if the table size is prime numberat least half of the entries will be visited figure the hash table using quadratic probe double hashing the quadratic probe distributes the keys by increasing steps in the probe sequence but the same sequence is followed by multiple keys that map to the same table