id
int64
0
25.6k
text
stringlengths
0
4.59k
13,600
once we have got to the end of the statementwe need to do one last check if the stack is emptythen we are fine and we can return true but if the stack is not emptythen we have some opening bracket which does not have matching closing bracket and we shall return false we can test the bracket-matcher with the following little codesl "{(foo)(bar)}[hello](((this)is) )test""{(foo)(bar)}[hello](((this)is)atest""{(foo)(bar)}[hello](((this)is) )test))for in slm check_brackets(sprint("{}{}format(sm)only the first of the three statements should match and when we run the codewe get the following outputtruefalsefalse the code works in summarythe push and pop operations of the stack data structure attract ( the stack data structure is simply enough but is used to implement whole range of functionality in the real world the back and forward buttons on the browser are made possible by stacks to be able to have undo and redo functionality in word processorsstacks are also used
13,601
queues another special type of list is the queue data structure this data structure is no different from the regular queue you are accustomed to in real life if you have stood in line at an airport or to be served your favorite burger at your neighborhood shopthen you should know how things work in queue queues are also very fundamental and important concept to grasp since many other data structures are built on them the way queue works is that the first person to join the queue usually gets served firstall things being equal the acronym fifo best explains this fifo stands for first infirst out when people are standing in queue waiting for their turn to be servedservice is only rendered at the front of the queue the only time people exit the queue is when they have been servedwhich only occurs at the very front of the queue by strict definitionit is illegal for people to join the queue at the front where people are being servedto join the queueparticipants must first move behind the last person in the queue the length of the queue does not matter this is the only legal or permitted way by which the queue accepts new entrants as human as we arethe queues that we form do not conform to strict rules it may have people who are already in the queue deciding to fall out or even have others substituting for them it is not our intent to model all the dynamics that happen in real queue abstracting what queue is and how it behaves enables us to solve plethora of challengesespecially in computing we shall provide various implementations of queue but all will revolve around the same idea of fifo we shall call the operation to add an element to the queue enqueue to remove an element from the queuewe will create dequeue operation anytime an element is enqueuedthe length or size of the queue increases by one converselydequeuing items reduce the number of elements in the queue by one
13,602
to demonstrate the two operationsthe following table shows the effect of adding and removing elements from queuequeue operation size contents operation results [queue object created enqueue "mark ['mark'mark added to queue enqueue "john ['mark','john'john added to queue size( ['mark','john'number of items in queue returned dequeue( ['mark'john is dequeued and returned dequeue( [mark is dequeued and returned queue(list-based queue to put into code everything discussed about queues to this pointlet' go ahead and implement very simple queue using python' list class this is to help us develop quickly and learn about queues the operations that must be performed on the queue are encapsulated in the listqueue classclass listqueuedef __init__(self)self items [self size in the initialization method __init__the items instance variable is set to []which means the queue is empty when created the size of the queue is also set to zero the more interesting methods are the enqueue and dequeue methods enqueue operation the enqueue operation or method uses the insert method of the list class to insert items (or dataat the front of the listdef enqueue(selfdata)self items insert( dataself size +
13,603
do note how we implement insertions to the end of the queue index is the first position in any list or array howeverin our implementation of queue using python listthe array index is the only place where new data elements are inserted into the queue the insert operation will shift existing data elements in the list by one position up and then insert the new data in the space created at index the following figure visualizes this processto make our queue reflect the addition of the new elementthe size is increased by oneself size + we could have used python' shift method on the list as another way of implementing the "insert at at the end of the dayan implementation is the overall objective of the exercise dequeue operation the dequeue operation is used to remove items from the queue with reference to the introduction to the topic of queuesthis operation captures the point where we serve the customer who joined the queue first and also waited the longestdef dequeue(self)data self items pop(self size - return data
13,604
the python list class has method called pop(the pop method does the following removes the last item from the list returns the removed item from the list back to the user or code that called it the last item in the list is popped and saved in the data variable in the last line of the methodthe data is returned consider the tunnel in the following figure as our queue to perform dequeue operationthe node with data is removed from the front of the queuethe resulting elements in the queue are as shown as followswhat can we say about the enqueue operationit is highly inefficient in more than one way the method has to first shift all the elements by one space imagine when there are million elements in list which need to be shifted around anytime new element is being added to the queue this will generally make the enqueue process very slow for large lists
13,605
stack-based queue yet another implementation of queue is to use two stacks once morethe python list class will be used to simulate stackclass queuedef __init__(self)self inbound_stack [self outbound_stack [the preceding queue class sets the two instance variables to empty lists upon initialization these are the stacks that will help us implement queue the stacks in this case are simply python lists that allow us to call push and pop methods on them the inbound_stack is only used to store elements that are added to the queue no other operation can be performed on this stack enqueue operation the enqueue method is what adds elements to the queuedef enqueue(selfdata)self inbound_stack append(datathe method is simple one that only receives the data the client wants to append to the queue this data is then passed to the append method of the inbound_stack in the queue class furthermorethe append method is used to mimic the push operationwhich pushes elements to the top of the stack to enqueue data onto the inbound_stackthe following code does justicequeue queue(queue enqueue( queue enqueue( queue enqueue( print(queue inbound_stacka command-line output of the inbound_stack inside the queue is as follows[
13,606
dequeue operation the dequeue operation is little more involved than its enqueue counterpart operation new elements added to our queue end up in the inbound_stack instead of removing elements from the inbound_stackwe shift our attention to the outbound_stack as we saidelements can be deleted from our queue only through the outbound_stackif not self outbound_stackwhile self inbound_stackself outbound_stack append(self inbound_stack pop()return self outbound_stack pop(the if statement first checks whether the outbound_stack is empty or not if it is not emptywe proceed to remove the element at the front of the queue by doing the followingreturn self outbound_stack pop(if the outbound_stack is empty insteadall the elements in the inbound_stack are moved to the outbound_stack before the front element in the queue is popped outwhile self inbound_stackself outbound_stack append(self inbound_stack pop()the while loop will continue to be executed as long as there are elements in the inbound_stack the statement self inbound_stack pop(will remove the latest element that was added to the inbound_stack and immediately pass the popped data to the self outbound_stack append(method call initiallyour inbound_stack was filled with the elements and
13,607
after executing the body of the while loopthe outbound_stack looks like thisthe last line in the dequeue method will return as the result of the pop operation on the outbound_stackreturn self outbound_stack pop(this leaves the outbound_stack with only two elements
13,608
the next time the dequeue operation is calledthe while loop will not be executed because there are no elements in the outbound_stackwhich makes the outer if statement fail the pop operation is called right away in that case so that only the element in the queue that has waited the longest is returned typical run of code to use this queue implementation is as followsqueue queue(queue enqueue( queue enqueue( queue enqueue( print(queue inbound_stackqueue dequeue(print(queue inbound_stackprint(queue outbound_stackqueue dequeue(print(queue outbound_stackthe output for the preceding code is as follows[ [[ [ the code sample adds elements to queue and prints out the elements within the queue the dequeue method is calledafter which change in the number of elements is observed when the queue is printed out again implementing queue with two stacks is popular question posed during interviews node-based queue using python list to implement queue is good starter to get the feel of how queues work it is completely possible for us to implement our own queue data structure by utilizing our knowledge of pointer structures queue can be implemented using doubly linked listand insertion and deletion operations on this data structure have time complexity of (
13,609
the definition for the node class remains the same as the node we defined when we touched on doubly linked listthe doubly linked list can be treated as queue if it enables fifo kind of data accesswhere the first element added to the list is the first to be removed queue class the queue class is very similar to that of the doubly linked list classclass queuedef __init__(self)self head none self tail none self count self head and self tail pointers are set to none upon creation of an instance of the queue class to keep count of the number of nodes in queuethe count instance variable is maintained here too and set to enqueue operation elements are added to queue object via the enqueue method the elements in this case are the nodesdef enqueue(selfdata)new_node node(datanonenoneif self head is noneself head new_node self tail self head elsenew_node prev self tail self tail next new_node self tail new_node self count + the enqueue method code is the same code already explained in the append operation of the doubly linked list it creates node from the data passed to it and appends it to the tail of the queueor points both self head and self tail to the newly created node if the queue is empty the total count of elements in the queue is increased by the line self count +
13,610
dequeue operation the other operation that makes our doubly linked list behave as queue is the dequeue method this method is what removes the node at the front of the queue to remove the first element pointed to by self headan if statement is useddef dequeue(self)current self head if self count = self count - self head none self tail none elif self count self head self head next self head prev none self count - current is initialized by pointing it to self head if self count is then it means only one node is in the list and invariably the queue thusto remove the associated node (pointed to by self head)the self head and self tail variables are set to none ifon the other handthe queue has many nodesthen the head pointer is shifted to point to self head' next node after the if statement is runthe method returns the node that was pointed to by head self count is decremented by one in either way the if statement execution path flows equipped with these methodswe have successfully implemented queueborrowing heavily from the idea of doubly linked list remember also that the only things transforming our doubly linked list into queue are the two methodsnamely enqueue and dequeue application of queues queues are used to implement variety of functionalities in computer land for instanceinstead of providing each computer on network with its own printera network of computers can be made to share one printer by queuing what each printer wants to print when the printer is ready to printit will pick one of the items (usually called jobsin the queue to print out operating systems also queue processes to be executed by the cpu let' create an application that makes use of queue to create bare-bones media player
13,611
media player queue most music player software allows users the chance to add songs to playlist upon hitting the play buttonall the songs in the main playlist are played one after the other the sequential playing of the songs can be implemented with queues because the first song to be queued is the first song that is played this aligns with the fifo acronym we shall implement our own playlist queue that plays songs in the fifo manner basicallyour media player queue will only allow for the addition of tracks and way to play all the tracks in the queue in full-blown music playerthreads would be used to improve how the queue is interacted withwhile the music player continues to be used to select the next song to be playedpausedor even stopped the track class will simulate musical trackfrom random import randint class trackdef __init__(selftitle=none)self title title self length randint( each track holds reference to the title of the song and also the length of the song the length is random number between and the random module provides the randint method to enable us generate the random numbers the class represents any mp track or file that contains music the random length of track is used to simulate the number of seconds it takes to play song or track to create few tracks and print out their lengthswe do the followingtrack track("white whistle"track track("butter butter"print(track lengthprint(track lengththe output of the preceding code is as follows your output may be different depending on the random length generated for the two tracks
13,612
nowlet' create our queue using inheritancewe simply inherit from the queue classimport time class mediaplayerqueue(queue)def __init__(self)super(mediaplayerqueueself__init__( call is made to properly initialize the queue by making call to super this class is essentially queue that holds number of track objects in queue to add tracks to the queuean add_track method is createddef add_track(selftrack)self enqueue(trackthe method passes track object to the enqueue method of the queue super class this willin effectcreate node using the track object (as the node' dataand point either the tailif the queue is not emptyor both head and tailif the queue is emptyto this new node assuming the tracks in the queue are played sequentially from the first track added to the last (fifo)then the play function has to loop through the elements in the queuedef play(self)while self count current_track_node self dequeue(print("now playing {}format(current_track_node data title)time sleep(current_track_node data lengthself count keeps count of when track is added to our queue and when tracks have been dequeued if the queue is not emptya call to the dequeue method will return the node (which houses the track objectat the front of the queue the print statement then accesses the title of the track through the data attribute of the node to further simulate the playing of trackthe time sleep(method halts program execution till the number of seconds of the track has elapsedtime sleep(current_track_node data length
13,613
the media player queue is made up of nodes when track is added to the queuethe track is hidden in newly created node and associated with the data attribute of the node that explains why we access node' track object through the data property of the node which is returned by the call to dequeueyou can seeinstead of our node object just storing just any datait stores tracks in this case let' take our music player for spintrack track("white whistle"track track("butter butter"track track("oh black star"track track("watch that chicken"track track("don' go"we create five track objects with random words as titlesprint(track lengthprint(track length> > the output should be different from what you get on your machine due to the random length nextan instance of the mediaplayerqueue class is createdmedia_player mediaplayerqueue(
13,614
the tracks will be added and the output of the play function should print out the tracks being played in the same order in which we queued themmedia_player add_track(track media_player add_track(track media_player add_track(track media_player add_track(track media_player add_track(track media_player play(the output of the preceding code is as follows>>now playing white whistle >>now playing butter butter >>now playing oh black star >>now playing watch that chicken >>now playing don' go upon execution of the programit can be seen that the tracks are played in the order in which they were queued when playing the trackthe system also pauses for the number of seconds equal to that of the length of the track summary in this we used our knowledge of linking nodes together to create other data structuresnamely stacks and queues we have seen how these data structures closely mimic stacks and queues in the real world concrete implementationstogether with their varying typeshave been shown we later applied the concept of stacks and queues to write real-life programs we shall consider trees in the next the major operations on tree will be discussedlikewise the different spheres in which to apply the data structure
13,615
trees tree is hierarchical form of data structure when we dealt with listsqueuesand stacksitems followed each other but in treethere is parent-child relationship between items to visualize what trees look likeimagine tree growing up from the ground now remove that image from your mind trees are normally drawn downwardso you would be better off imagining the root structure of the tree growing downward at the top of every tree is the so-called root node this is the ancestor of all other nodes in the tree trees are used for number of thingssuch as parsing expressionsand searches certain document typessuch as xml and htmlcan also be represented in tree form we shall look at some of the uses of trees in this in this we will cover the following areasterms and definitions of trees binary trees and binary search trees tree traversal
13,616
terminology let' consider some terms associated with trees to understand treeswe need to first understand the basic ideas on which they rest the following figure contains typical tree consisting of character nodes lettered through to here is list of terms associated with treenodeeach circled alphabet represents node node is any structure that holds data root nodethe root node is the only node from which all other nodes come tree with an undistinguishable root node cannot be considered as tree the root node in our tree is the node sub-treea sub-tree of tree is tree with its nodes being descendant of some other tree nodes fkand form sub-tree of the original tree consisting of all the nodes degreethe number of sub-trees of given node tree consisting of only one node has degree of this one tree node is also considered as tree by all standards the degree of node is leaf nodethis is node with degree of nodes jeklhmand are all leaf nodes edgethe connection between two nodes an edge can sometimes connect node to itselfmaking the edge appear as loop
13,617
parenta node in the tree with other connecting nodes is the parent of those nodes node is the parent of nodes deand childthis is node connected to its parent nodes and are children of node athe parent and root node siblingall nodes with the same parent are siblings this makes the nodes and siblings levelthe level of node is the number of connections from the root node the root node is at level nodes and are at level height of treethis is the number of levels in tree our tree has height of depththe depth of node is the number of edges from the root of the tree to that node the depth of node is we shall begin our treatment of trees by considering the node in tree and abstracting class tree nodes just as was the case with other data structures that we encounteredsuch as lists and stackstrees are built up of nodes but the nodes that make up tree need to contain data about the parent-child relationship that we mentioned earlier let us now look at how to build binary tree node class in pythonclass nodedef __init__(selfdata)self data data self right_child none self left_child none just like in our previous implementationsa node is container for data and holds references to other nodes being binary tree nodethese references are to the left and the right children to test this class outwe first create few nodesn node("root node" node("left child node" node("right child node" node("left grandchild node"
13,618
nextwe connect the nodes to each other we let be the root node with and as its children finallywe hook as the left child to so that we get few iterations when we traverse the left sub-treen left_child right_child left_child once we have our tree structure set upwe are ready to traverse it as mentioned previouslywe shall traverse the left sub-tree we print out the node and move down the tree to the next left node we keep doing this until we have reached the end of the left subtreecurrent while currentprint(current datacurrent current left_child as you will probably have noticedthis requires quite bit of work in the client codeas you have to manually build up the tree structure binary trees binary tree is one in which each node has maximum of two children binary trees are very common and we shall use them to build up bst implementation in python the following figure is an example of binary tree with being the root nodeeach child is identified as being the right or left child of its parent since the parent node is also node by itselfeach node will hold reference to right and left node even if the nodes do not exist regular binary tree has no rules as to how elements are arranged in the tree it only satisfies the condition that each node should have maximum of two children
13,619
binary search trees binary search tree (bstis special kind of binary tree that isit is tree that is structurally binary tree functionallyit is tree that stores its nodes in such way to be able to search through the tree efficiently there is structure to bst for given node with valueall the nodes in the left sub-tree are less than or equal to the value of that node alsoall the nodes in the right sub-tree of this node are greater than that of the parent node as an exampleconsider the following treethis is an example of bst testing our tree for the properties of bstyou realize that all the nodes in the left sub-tree of the root node have value less than likewiseall the nodes in the right sub-tree have value that is greater than this property applies to all the nodes in bstwith no exceptionsdespite the fact that the preceding figure looks similar to the previous figureit does not qualify as bst node is greater than the root node howeverit is located to the left of the root node node is to the right sub-tree of its parent node which is incorrect
13,620
binary search tree implementation let us begin our implementation of bst we will want the tree to hold reference to its own root nodeclass treedef __init__(self)self root_node none that' all that is needed to maintain the state of tree let' examine the main operations on the tree in the next section binary search tree operations there are essentially two operations that are needful for having usable bst these are the insert and remove operations these operations must occur with the one rule that they must maintain the principle that gives the bst its structure before we tackle the insertion and removal of nodeslet' discuss some equally important operations that will help us better understand the insert and remove operations finding the minimum and maximum nodes the structure of the bst makes looking for the node with the maximum and minimum values very easy to find the node with smallest valuewe start our traversal from the root of the tree and visit the left node each time we reach sub-tree we do the opposite to find the node with the biggest value in the tree
13,621
we move down from node to to to get to the node with smallest value likewisewe go down to node which is the node with the largest value this same means of finding the minimum and maximum nodes applies to sub-trees too the minimum node in the sub-tree with root node is the node within that sub-tree with the maximum value is the method that returns the minimum node is as followsdef find_min(self)current self root_node while current left_childcurrent current left_child return current the while loop continues to get the left node and visits it until the last left node points to none it is very simple method the method to return the maximum node does the oppositewhere current left_child now becomes current right_child it takes (hto find the minimum or maximum value in bstwhere is the height of the tree inserting nodes one of the operations on bst is the need to insert data as nodes whereas in our first implementationwe had to insert the nodes ourselveshere we are going to let the tree be in charge of storing its data in order to make search possiblethe nodes must be stored in specific way for each given nodeits left child node will hold data that is less than its own valueas already discussed that node' right child node will hold data greater than that of its parent node we are going to create new bst of integers by starting with the data to do thiswe will create node with its data attribute set to nowto add the second node with value is compared with the root node
13,622
since is greater than it will be put in the left sub-tree of node our bst will look as followsthe tree satisfies the bst rulewhere all the nodes in the left sub-tree are less than its parent to add another node of value to the treewe start from the root node with value and do comparisonsince is greater than the node with value is situated to the right of this root what happens when we want to add node that is equal to an existing nodewe will simply add it as left node and maintain this rule throughout the structure if node already has child in the place where the new node goesthen we have to move down the tree and attach it let' add another node with value starting from the root of the treewe do comparison between and the comparison reveals that is less than so we move our attention to the left node of which is the node with value
13,623
we compare with and since is less than we move level below node and to its left but there is no node there thereforewe create node with the value and associate it with the left pointer of node to obtain the following structureso farwe have been dealing only with nodes that contain only integers or numbers for numbersthe idea of greater than and lesser than are clearly defined strings would be compared alphabeticallyso there are no major problems there either but if you want to store your own custom data types inside bstyou would have to make sure that your class supports ordering let' now create function that enables us to add data as nodes to the bst we begin with function declarationdef insert(selfdata)by nowyou will be used to the fact that we encapsulate the data in node this waywe hide away the node class from the client codewho only needs to deal with the treenode node(dataa first check will be to find out whether we have root node if we don'tthe new node becomes the root node (we cannot have tree without root node)if self root_node is noneself root_node node else
13,624
as we walk down the treewe need to keep track of the current node we are working onas well as its parent the variable current is always used for this purposecurrent self root_node parent none while trueparent current here we must perform comparison if the data held in the new node is less than the data held in the current nodethen we check whether the current node has left child node if it doesn'tthis is where we insert the new node otherwisewe keep traversingif node data current datacurrent current left_child if current is noneparent left_child node return now we take care of the greater than or equal case if the current node doesn' have right child nodethen the new node is inserted as the right child node otherwisewe move down and continue looking for an insertion pointelsecurrent current right_child if current is noneparent right_child node return insertion of node in bst takes ( )where is the height of the tree deleting nodes another important operation on bst is the deletion or removal of nodes there are three scenarios that we need to cater for during this process the node that we want to remove might have the followingno children one child two children
13,625
the first scenario is the easiest to handle if the node about to be removed has no childrenwe simply detach it from its parentbecause node has no childrenwe will simply dissociate it from its parentnode on the other handwhen the node we want to remove has one childthe parent of that node is made to point to the child of that particular nodein order to remove node which has as its only childnode we point the left pointer of node to node the relationship between the parent node and child has to be preserved that is why we need to take note of how the child node is connected to its parent (which is the node about to be deletedthe child node of the deleted node is stored then we connect the parent of the deleted node to that child node
13,626
more complex scenario arises when the node we want to delete has two childrenwe cannot simply replace node with either node or what we need to do is to find the next biggest descendant of node this is node to get to node we move to the right node of node and then move left to find the leftmost node node is called the in-order successor of node the second step resembles the move to find the maximum node in sub-tree we replace the value of node with the value and remove node in removing node we end up with simpler form of node removal that has been addressed previously node has no childrenso we apply the rule for removing nodes without children accordingly our node class does not have reference to parent as suchwe need to use helper method to search for and return the node with its parent node this method is similar to the search methoddef get_node_with_parent(selfdata)parent none current self root_node if current is nonereturn (parentnonewhile trueif current data =datareturn (parentcurrentelif current data dataparent current current current left_child elseparent current current current right_child return (parentcurrent
13,627
the only difference is that before we update the current variable inside the loopwe store its parent with parent current the method to do the actual removal of node begins with this searchdef remove(selfdata)parentnode self get_node_with_parent(dataif parent is none and node is nonereturn false get children count children_count if node left_child and node right_childchildren_count elif (node left_child is noneand (node right_child is none)children_count elsechildren_count we pass the parent and the found node to parent and node respectively with the line parentnode self get_node_with_parent(datait is helpful to know the number of children that the node we want to delete has that is the purpose of the if statement after thiswe need to begin handling the various conditions under which node can be deleted the first part of the if statement handles the case where the node has no childrenif children_count = if parentif parent right_child is nodeparent right_child none elseparent left_child none elseself root_node none if parentis used to handle cases where there is bst that has only one node in the whole of the three in the case where the node about to be deleted has only one childthe elif part of the if statement does the followingelif children_count = next_node none if node left_childnext_node node left_child
13,628
elsenext_node node right_child if parentif parent left_child is nodeparent left_child next_node elseparent right_child next_node elseself root_node next_node next_node is used to keep track of where the single node pointed to by the node we want to delete is we then connect parent left_child or parent right_child to next_node lastlywe handle the condition where the node we want to delete has two childrenelseparent_of_leftmost_node node leftmost_node node right_child while leftmost_node left_childparent_of_leftmost_node leftmost_node leftmost_node leftmost_node left_child node data leftmost_node data in finding the in-order successorwe move to the right node with leftmost_node node right_child as long as there exists left nodeleftmost_node left_child will evaluate to true and the while loop will run when we get to the leftmost nodeit will either be leaf node (meaning that it will have no child nodeor have right child we update the node about to be removed with the value of the in-order successor with node data leftmost_node dataif parent_of_leftmost_node left_child =leftmost_nodeparent_of_leftmost_node left_child leftmost_node right_child elseparent_of_leftmost_node right_child leftmost_node right_child the preceding statement allows us to properly attach the parent of the leftmost node with any child node observe how the right-hand side of the equals sign stays unchanged that is because the in-order successor can only have right child as its only child the remove operation takes ( )where is the height of the tree
13,629
searching the tree since the insert method organizes data in specific waywe will follow the same procedure to find the data in this implementationwe will simply return the data if it was found or none if the data wasn' founddef search(selfdata)we need to start searching at the very topthat isat the root nodecurrent self root_node while truewe may have passed leaf nodein which case the data doesn' exist in the tree and we return none to the client codeif current is nonereturn none we might also have found the datain which case we return itelif current data is datareturn data as per the rules for how data is stored in the bstif the data we are searching for is less than that of the current nodewe need to go down the tree to the leftelif current data datacurrent current left_child now we only have one option leftthe data we are looking for is greater than the data held in the current nodewhich means we go down the tree to the rightelsecurrent current right_child finallywe can write some client code to test how the bst works we create tree and insert few numbers between and then we search for all the numbers in that range the ones that exist in the tree get printedtree tree(tree insert( tree insert( tree insert( tree insert( tree insert(
13,630
for in range( )found tree search(iprint("{}{}format(ifound)tree traversal visiting all the nodes in tree can be done depth first or breadth first these modes of traversal are not peculiar to only binary search trees but trees in general depth-first traversal in this traversal modewe follow branch (or edgeto its limit before recoiling upwards to continue traversal we will be using the recursive approach for the traversal there are three forms of depth-first traversalnamely in-orderpre-orderand post-order in-order traversal and infix notation most of us are probably used to this way of representing an arithmetic expressionsince this is the way we are normally taught in schools the operator is inserted (infixedbetween the operandsas in when necessaryparentheses can be used to build more complex expression( ( in this mode of traversalyou would visit the left sub-treethe parent nodeand finally the right sub-tree the recursive function to return an in-order listing of nodes in tree is as followsdef inorder(selfroot_node)current root_node if current is nonereturn self inorder(current left_childprint(current dataself inorder(current right_childwe visit the node by printing the node and making two recursive calls with current left_child and current right_child
13,631
pre-order traversal and prefix notation prefix notation is commonly referred to as polish notation herethe operator comes before its operandsas in since there is no ambiguity of precedenceparentheses are not required to traverse tree in pre-order modeyou would visit the nodethe left sub-treeand the right sub-tree nodein that order prefix notation is well known to lisp programmers the recursive function for this traversal is as followsdef preorder(selfroot_node)current root_node if current is nonereturn print(current dataself preorder(current left_childself preorder(current right_childnote the order in which the recursive call is made post-order traversal and postfix notation postfix or reverse polish notation (rpnplaces the operator after its operandsas in as is the case with polish notationthere is never any confusion over the precedence of operatorsso parentheses are never needed in this mode of traversalyou would visit the left sub-treethe right sub-treeand lastly the root node the post-order method is as followsdef postorder(selfroot_node)current root_node if current is nonereturn self postorder(current left_childself postorder(current right_childprint(current data
13,632
breadth-first traversal this kind of traversal starts from the root of tree and visits the node from one level of the tree to the otherthe node at level is node we visit this node by printing out its value nextwe move to level and visit the nodes on that levelwhich are nodes and on the last levellevel we visit nodes and the complete output of such traversal is and this mode of traversal is made possible by using queue data structure starting with the root nodewe push it into queue the node at the front of the queue is accessed (dequeuedand either printed and stored for later use the left node is added to the queue followed by the right node since the queue is not emptywe repeat the process dry run of the algorithm will enqueue the root node dequeueand accessor visit the node nodes and are enqueued as they are the left and right nodes respectively node is dequeued in order to be visited its left and right nodes and are enqueued at this pointthe node at the front of the queue is we dequeue and visit node after which we enqueue its left and right nodes so the process continues until the queue is empty the algorithm is as followsfrom collections import deque class treedef breadth_first_traversal(self)list_of_nodes [traversal_queue deque([self root_node]
13,633
we enqueue the root node and keep list of the visited nodes in the list_of_nodes list the dequeue class is used to maintain queuewhile len(traversal_queue node traversal_queue popleft(list_of_nodes append(node dataif node left_childtraversal_queue append(node left_childif node right_childtraversal_queue append(node right_childreturn list_of_nodes if the number of elements in the traversal_queue is greater than zerothe body of the loop is executed the node at the front of the queue is popped off and appended to the list_of_nodes list the first if statement will enqueue the left child node of the node provided left node exists the second if statement does the same for the right child node the list_of_nodes is returned in the last statement benefits of binary search tree we shall now briefly look at what makes bst better idea than using list for data that needs to be searched let us assume that we have the following dataset and using listthe worst-case scenario would require you to search through the entire list of seven elements before finding the search termsearching for requires six jumps
13,634
with treethe worst-case scenario is three comparisonssearching for requires two steps noticehoweverthat if you insert the elements into the tree in the order then the tree would not be more efficient than the list we would have to balance the tree firstso not only is it important to use bst but choosing self-balancing tree helps to improve the search operation
13,635
expression trees the tree structure is also used to parse arithmetic and boolean expressions for examplethe expression tree for would look as followsfor slightly more complex expression( ( - )we would get the followingparsing reverse polish expression now we are going to build up tree for an expression written in postfix notation then we will calculate the result we will use simple tree implementation to keep it really simplesince we are going to grow the tree by merging smaller treeswe only need tree node implementationclass treenodedef __init__(selfdata=none)self data data self right none self left none in order to build the treewe are going to enlist the help of stack you will see why soon but for the time beinglet us just create an arithmetic expression and set up our stackexpr " *split(stack stack(
13,636
since python is language that tries hard to have sensible defaultsits split(method splits on whitespace by default (if you think about itthis is most likely what you would expect as well the result is going to be that expr is list with the values + and each element of the expr list is going to be either an operator or an operand if we get an operand then we embed it in tree node and push it onto the stack if we get an operatoron the other handthen we embed the operator into tree node and pop its two operands into the node' left and right children here we have to take care to ensure that the first pop goes into the right childotherwise we will have problems with subtraction and division here is the code to build the treefor term in exprif term in "+-*/"node treenode(termnode right stack pop(node left stack pop(elsenode treenode(int(term)stack push(nodenotice that we perform conversion from string to int in the case of an operand you could use float(insteadif you wanted to support floating point operands at the end of this operationwe should have one single element in the stackand that holds the full tree we may now want to be able to evaluate the expression we build the following little function to help usdef calc(node)if node data is "+"return calc(node leftcalc(node rightelif node data is "-"return calc(node leftcalc(node rightelif node data is "*"return calc(node leftcalc(node rightelif node data is "/"return calc(node leftcalc(node rightelsereturn node data
13,637
this function is very simple we pass in node if the node contains an operandthen we simply return that value if we get an operatorhoweverthen we perform the operation that the operator representson the node' two children howeversince one or more of the children could also contain either operators or operandswe call the calc(function recursively on the two child nodes (bearing in mind that all the children of every node are also nodesnow we just need to pop the root node off the stack and pass it into the calc(function and we should have the result of the calculationroot stack pop(result calc(rootprint(resultrunning this program should yield the result which is the result of ( ( balancing trees earlierwe mentioned that if nodes are inserted into the tree in sequential orderthen the tree behaves more or less like listthat iseach node has exactly one child node we normally would like to reduce the height of the tree as much as possibleby filling up each row in the tree this process is called balancing the tree there are number of types of self-balancing treessuch as red-black treesaa treesand scapegoat trees these balance the tree during each operation that modifies the treesuch as insert or delete there are also external algorithms that balance tree the benefit of these is that you wouldn' need to balance the tree on every single operationbut could rather leave balancing to the point when you need it heaps at this pointwe shall briefly introduce the heap data structure heap is specialization of tree in which the nodes are ordered in specific way heaps are divided into max and min heaps in max heapeach parent node must always be greater than or equal to its children it follows that the root node must be the greatest value in the tree min heap is the opposite each parent node must be less than or equal to both its children as consequencethe root node holds the lowest value
13,638
heaps are used for number of different things for onethey are used to implement priority queues there is also very efficient sorting algorithmcalled heap sortthat uses heaps we are going to study these in depth in subsequent summary in this we have looked at tree structures and some example uses of them we studied binary trees in particularwhich is subtype of trees where each node has at most two children we looked at how binary tree can be used as searchable data structure with bst we saw thatin most casesfinding data in bst is faster than in linked listalthough this is not the case if the data is inserted sequentiallyunless of course the tree is balanced the breadthand depth-first search traversal modes were also implemented using queue recursion we also looked at how binary tree can be used to represent an arithmetic or boolean expression we built up an expression tree to represent an arithmetic expression we showed how to use stack to parse an expression written in rpnbuild up the expression treeand finally traverse it to get the result of the arithmetic expression finallywe mentioned heapsa specialization of tree structure we have tried to at least lay down the theoretical foundation for the heap in this so that we can go on to implement heaps for different purposes in upcoming
13,639
hashing and symbol tables we have previously looked at listswhere items are stored in sequence and accessed by index number index numbers work well for computers they are integers so they are fast and easy to manipulate howeverthey don' always work so well for us if we have an address book entryfor examplewith index number that number doesn' tell us much there is nothing to link particular contact with number it just happens to be the next available position in the list in this we are going to look at similar structurea dictionary dictionary uses keyword instead of an index number soif that contact was called jameswe would probably use the keyword james to locate the contact that isinstead of accessing the contact by calling contacts [ ]we would use contacts ["james"dictionaries are often built using hash tables as the name suggestshash tables rely on concept called hashing that is where we are going to begin our discussion we will cover the following topics in this hashing hash tables different functions with elements hashing hashing is the concept of converting data of arbitrary size into data of fixed size little bit more specificallywe are going to use this to turn strings (or possibly other data typesinto integers this possibly sounds more complex than it is so let' look at an example we want to hash the expression hello worldthat iswe want to get numeric value that we could say represents the string
13,640
by using the ord(functionwe can get the ordinal value of any character for examplethe ord(' 'function gives to get the hash of the whole stringwe could just sum the ordinal numbers of each character in the stringsum(map(ord'hello world') this works fine howevernote that we could change the order of the characters in the string and get the same hashsum(map(ord'world hello') and the sum of the ordinal values of the characters would be the same for the string gello xorld as wellsince has an ordinal value which is one less than that of hand has an ordinal value that is one greater than that of whencesum(map(ord'gello xorld') perfect hashing functions perfect hashing function is one in which each string (as we are limiting the discussion to strings for nowis guaranteed to be unique in practicehashing functions normally need to be very fastso trying to create function that will give each string unique hash value is normally not possible insteadwe live with the fact that we sometimes get collisions (two or more strings having the same hash value)and when that happenswe come up with strategy for resolving them
13,641
in the meantimewe can at least come up with way to avoid some of the collisions we couldfor exampleadd multiplierso that the hash value for each character becomes the multiplier valuemultiplied by the ordinal value of the character the multiplier then increases as we progress through the string this is shown in the following functiondef myhash( )mult hv for ch in shv +mult ord(chmult + return hv we can test this function on the strings that we used earlierfor item in ('hello world''world hello''gello xorld')print("{}{}format(itemmyhash(item))running the programwe get the following outputpython hashtest py hello world world hello gello xorld note that the last row is the result of multiplying the values in rows and such that equals as an example this time we get different hash values for our strings of coursethis doesn' mean that we have perfect hash let us try the strings ad and gapython hashtest py ad ga
13,642
there we still get the same hash value for two different strings as we have said beforethis doesn' have to be problembut we need to devise strategy for resolving collisions we shall look at that shortlybut first we will study an implementation of hash table hash table hash table is form of list where elements are accessed by keyword rather than an index number at leastthis is how the client code will see it internallyit will use slightly modified version of our hashing function in order to find the index position in which the element should be inserted this gives us fast lookupssince we are using an index number which corresponds to the hash value of the key we start by creating class to hold hash table items these need to have key and valuesince our hash table is key-value storeclass hashitemdef __init__(selfkeyvalue)self key key self value value this gives us very simple way to store items nextwe start working on the hash table class itself as usualwe start off with constructorclass hashtabledef __init__(self)self size self slots [none for in range(self size)self count the hash table uses standard python list to store its elements we could equally well have used the linked list that we developed previouslybut right now our focus is on understanding the hash tableso we shall use what is at our disposal we set the size of the hash table to elements to start with laterwe will look at strategies for how to grow the table as we begin filling it up we now initialize list containing elements these elements are often referred to as slots or buckets finallywe add counter for the number of actual hash table elements we have
13,643
it is important to notice the difference between the size and count of table size of table refers to the total number of slots in the table (used or unusedcount of the tableon the other handsimply refers to the number of slots that are filledor put another waythe number of actual key-value pairs we have added to the table nowwe are going to add our hashing function to the table it will be similar to what we evolved in the section on hashing functionsbut with slight differencewe need to ensure that our hashing function returns value between and (the size of the tablea good way of doing so is to return the remainder of dividing the hash by the size of the tablesince the remainder is always going to be an integer value between and as the hashing function is only meant to be used internally by the classwe put an underscore(_at the beginning of the name to indicate this this is normal python convention for indicating that something is meant for internal usedef _hash(selfkey)mult hv for ch in keyhv +mult ord(chmult + return hv self size for the time beingwe are going to assume that keys are strings we shall discuss how one can use non-string keys later for nowjust bear in mind that the _hash(function is going to generate the hash value of string putting elements we add elements to the hash with the put(function and retrieve with the get(function firstwe will look at the implementation of the put(function we start by embedding the key and the value into the hashitem class and computing the hash of the keydef put(selfkeyvalue)item hashitem(keyvalueh self _hash(keynow we need to find an empty slot we start at the slot that corresponds to the hash value of the key if that slot is emptywe insert our item there
13,644
howeverif the slot is not empty and the key of the item is not the same as our current keythen we have collision this is where we need to figure out way to handle conflict we are going to do this by adding one to the previous hash value we had and getting the remainder of dividing this value by the size of the hash table this is linear way of resolving collisions and it is quite simplewhile self slots[his not noneif self slots[hkey is keybreak ( self size we have found our insertion point if this is new element (that isit contained none previously)then we increase the count by one finallywe insert the item into the list at the required positionif self slots[his noneself count + self slots[hitem getting elements the implementation of the get(method should return the value that corresponds to key we also have to decide what to do in the event that the key does not exist in the table we start by calculating the hash of the keydef get(selfkey) self _hash(key
13,645
nowwe simply start looking through the list for an element that has the key we are searching forstarting at the element which has the hash value of the key that was passed in if the current element is not the correct onethenjust like in the put(methodwe add one to the previous hash value and get the remainder of dividing this value by the size of the list this becomes our new index if we find an element that contains nonewe stop looking if we find our keywe return the valuewhile self slots[his not noneif self slots[hkey is keyreturn self slots[hvalue ( self size finallywe decide what to do if the key was not found in the table here we will choose to return none another good alternative may be to raise an exceptionreturn none testing the hash table to test our hash tablewe create hashtableput few elements in itthen try to retrieve these we will also try to get( key that does not exist remember the two strings ad and ga which returned the same hash value by our hashing functionfor good measurewe throw those in as welljust to see that the collision is properly resolvedht hashtable(ht put("good""eggs"ht put("better""ham"ht put("best""spam"ht put("ad""do not"
13,646
ht put("ga""collide"for key in ("good""better""best""worst""ad""ga") ht get(keyprint(vrunning this returns the followingpython hashtable py eggs ham spam none do not collide as you can seelooking up the key worst returns nonesince the key does not exist the keys ad and ga also return their corresponding valuesshowing that the collision between them is dealt with using [with the hash table using the put(and get(methods doesn' look very goodhowever we want to be able to treat our hash table as listthat iswe would like to be able to use ht["good"instead of ht get("good"this is easily done with the special methods __setitem__(and __getitem__()def __setitem__(selfkeyvalue)self put(keyvaluedef __getitem__(selfkey)return self get(keyour test code can now look like this insteadht hashtable(ht["good""eggsht["better""hamht["best""spamht["ad""do notht["ga""collidefor key in ("good""better""best""worst""ad""ga")
13,647
ht[keyprint(vprint("the number of elements is{}format(ht count)notice that we also print the number of elements in the hash table this is useful for our next discussion non-string keys in most casesit makes more sense to just use strings for the keys howeverif necessaryyou could use any other python type if you create your own class that you want to use as keyyou will probably want to override the special __hash__(function for that classso that you get reliable hash values note that you would still have to calculate the modulo (%of the hash value and the size of the hash table to get the slot that calculation should happen in the hash table and not in the key classsince the table knows its own size (the key class should not know anything about the table that it belongs togrowing hash table in our examplethe hash table' size was set to obviouslyas we add elements to the listwe begin to fill up the empty slots at some pointall the slots will be filled up and the table will be full to avoid thiswe can grow the table when it is getting full to do thiswe compare the size and the count remember that size held the total number of slots and count the number of those slots that contained elementswellif count equals size then we have filled up the table the hash table' load factor gives us an indication of how large portion of the available slots are being used it is defined as follows
13,648
as the load factor approaches we need to grow the table in factwe should do it before it gets there in order to avoid gets becoming too slow value of may be good value in which to grow the table the next question is how much to grow the table by one strategy would be to simply double the size of the table open addressing the collision resolution mechanism we used in our examplelinear probingis an example of an open addressing strategy linear probing is really simple since we use fixed interval between our probes there are other open addressing strategies as well but they all share the idea that there is an array of slots when we want to insert keywe check whether the slot already has an item or not if it doeswe look for the next available slot if we have hash table that contains slotsthen is the maximum number of elements in that hash moreoveras the load factor increasesit will take longer to find the insertion point for the new element because of these limitationswe may prefer to use different strategy to resolve collisionssuch as chaining chaining chaining is strategy for resolving conflicts and avoiding the limit to the number of elements in hash table in chainingthe slots in the hash table are initialized with empty lists
13,649
when an element is insertedit will be appended to the list that corresponds to that element' hash value that isif you have two elements that both have the hash value these two elements will both be added to the list that exists in slot of the hash tablethe preceding diagram shows list of entries with hash value chaining then avoids conflict by allowing multiple elements to have the same hash value it also avoids the problem of insertions as the load factor increasessince we don' have to look for slot moreoverthe hash table can hold more values than the number of available slotssince each slot holds list that can grow of courseif particular slot has many itemssearching them can get very slowsince we have to do linear search through the list until we find the element that has the key we want this can slow down retrievalwhich is not goodsince hash tables are meant to be efficientthe preceding diagram demonstrates linear search through list items until we find match
13,650
instead of using lists in the table slotswe could use another structure that allows for fast searching we have already looked at binary search trees (bstswe could simply put an (initially emptybst in each slotslot holds bst which we search for the key but we would still have potential problemdepending on the order in which the items were added to the bstwe could end up with search tree that is as inefficient as list that iseach node in the tree has exactly one child to avoid thiswe would need to ensure that our bst is self-balancing symbol tables symbol tables are used by compilers and interpreters to keep track of the symbols that have been declared and information about them symbol tables are often built using hash tablessince it is important to efficiently retrieve symbol in the table let us look at an example suppose we have the following python codename "joeage here we have two symbolsname and age they belong to namespacewhich could be __main__but it could also be the name of module if you placed it there each symbol has valuename has the value joe and age has the value symbol table allows the compiler or the interpreter to look these values up the symbols name and age become the keys in our hash table all the other information associated with itsuch as the valuebecome part of the value of the symbol table entry not only variables are symbolsbut functions and classes as well they will all be added to our symbol tableso that when any one of them needs to be accessedthey are accessible from the symbol table
13,651
in pythoneach module that is loaded has its own symbol table the symbol table is given the name of that module this waymodules act as namespaces we can have multiple symbols called ageas long as they exist in different symbol tables to access either onewe access it through the appropriate symbol tablesummary in this we have looked at hash tables we looked at how to write hashing function to turn string data into integer data then we looked at how we can use hashed keys to quickly and efficiently look up the value that corresponds to key we also noticed how hashing functions are not perfect and that several strings can end up having the same hash value this led us to look at collision resolution strategies we looked at growing hash table and how to look at the load factor of the table in order to determine exactly when to grow the hash in the last section of the we studied symbol tableswhich often are built using hash tables symbol tables allow compiler or an interpreter to look up symbol (variablefunctionclassand so onthat has been defined and retrieve all information about it in the next we will talk about graphs and other algorithms
13,652
graphs and other algorithms in this we are going to talk about graphs this is concept that comes from the branch of mathematics called graph theory graphs are used to solve number of computing problems they also have much less structure than other data structures we have looked at and things like traversal can be much more unconventionalas we shall see by the end of this you should be able to do the followingunderstand what graphs are know the types of graphs and their constituents know how to represent graph and traverse it get fundamental idea of what priority queues are be able to implement priority queue be able to determine the ith smallest element in list graphs graph is set of vertices and edges that form connections between the vertices in more formal approacha graph is an ordered pair of set of vertices and set of edges given as (vein formal mathematical notation
13,653
an example of graph is given herelet' now go through some definitions of graphnode or vertexa pointusually represented by dot in graph the vertices or nodes are abcdand edgethis is connection between two vertices the line connecting and is an example of an edge loopwhen an edge from node is incident on itselfthat edge forms loop degree of vertexthis is the number of vertices that are incident on given vertex the degree of vertex is adjacencythis refers to the connection(sbetween node and its neighbor the node is adjacent to node because there is an edge between them patha sequence of vertices where each adjacent pair is connected by an edge directed and undirected graphs graphs can be classified based on whether they are undirected or directed an undirected graph simply represents edges as lines between the nodes there is no additional information about the relationship between the nodes than the fact that they are connected
13,654
in directed graphthe edges provide orientation in addition to connecting nodes that isthe edgeswhich will be drawn as lines with an arrowwill point in which direction the edge connects the two nodesthe arrow of an edge determines the flow of direction one can only move from to in the preceding diagram not to
13,655
weighted graphs weighted graph adds bit of extra information to the edges this can be numerical value that indicates something let' sayfor examplethat the following graph indicates different ways to get from point to point you can either go straight from to dor choose to pass through and associated with each edge is the amount of time in minutes the journey to the next node will takeperhaps the journey ad would require you to ride bike (or walkb and might represent bus stops at you would have to change to different bus finallycd may be short walk to reach in this examplead and abcd represent two different paths path is simply sequence of edges that you pass through between two nodes following these pathsyou see that the total journey ad takes minuteswhereas the journey abcd takes minutes if your only concern is timeyou would be better off traveling along abcdeven with the added inconvenience of changing buses the fact that edges can be directed and may hold other informationsuch as time taken or whatever other value the move along path is associated withindicates something interesting in previous data structures that we have worked withthe lines we have drawn between nodes have simply been connectors even when they had arrows pointing from node to anotherthat was easy to represent in the node class by using next or previousparent or child with graphsit makes sense to see edges as objects just as much as nodes just like nodesedges can contain extra information that is necessary to follow particular path
13,656
graph representation graphs can be represented in two main forms one way is to use an adjacency matrix and the other is to use an adjacency list we shall be working with the following figure to develop both types of representation for graphsadjacency list simple list can be used to present graph the indices of the list will represent the nodes or vertices in the graph at each indexthe adjacent nodes to that vertex can be stored
13,657
the numbers in the box represent the vertices index represents vertex awith its adjacent nodes being and using list for the representation is quite restrictive because we lack the ability to directly use the vertex labels dictionary is therefore more suited to represent the graph in the diagramwe can use the following statementsgraph dict(graph[' '[' '' 'graph[' '[' ',' 'graph[' '[' '' '' ',' 'graph[' '[' '' 'graph[' '[' 'now we easy establish that vertex has the adjacent vertices and vertex has vertex as its only neighbor adjacency matrix another approach by which graph can be represented is by using an adjacency matrix matrix is two-dimensional array the idea here is to represent the cells with or depending on whether two vertices are connected by an edge given an adjacency listit should be possible to create an adjacency matrix sorted list of keys of graph is requiredmatrix_elements sorted(graph keys()cols rows len(matrix_elementsthe length of the keys is used to provide the dimensions of the matrix which are stored in cols and rows these values in cols and rows are equaladjacency_matrix [[ for in range(rows)for in range(cols)edges_list [we then set up cols by rows arrayfilling it with zeros the edges_list variable will store the tuples that form the edges of in the graph for examplean edge between node and will be stored as (abthe multidimensional array is filled using nested for loopfor key in matrix_elementsfor neighbor in graph[key]edges_list append((key,neighbor)
13,658
the neighbors of vertex are obtained by graph[keythe key in combination with the neighbor is then used to create the tuple stored in edges_list the output of the iteration is as follows[(' '' ')(' '' ')(' '' ')(' '' ')(' '' ')(' '' ')(' '' ')(' '' ')(' '' ')(' '' ')(' '' ')what needs to be done now is to fill the our multidimensional array by using to mark the presence of an edge with the line adjacency_matrix[index_of_first_vertex][index_of_second_vertex for edge in edges_listindex_of_first_vertex matrix_elements index(edge[ ]index_of_second_vertex matrix_elements index(edge[ ]adjacecy_matrix[index_of_first_vertex][index_of_second_vertex the matrix_elements array has its rows and cols starting from through to with the indices through to the for loop iterates through our list of tuples and uses the index method to get the corresponding index where an edge is to be stored the adjacency matrix produced looks like so[ [ [ [ [ at column and row the there represents the absence of an edge between and on column and row there is an edge between and graph traversal since graphs don' necessarily have an ordered structuretraversing graph can be more involving traversal normally involves keeping track of which nodes or vertices have already been visited and which ones have not common strategy is to follow path until dead end is reachedthen walking back up until there is point where there is an alternative path we can also iteratively move from one node to another in order to traverse the full graph or part of it in the next sectionwe will discuss breadth and depth-first search algorithms for graph traversal
13,659
breadth-first search the breadth-first search algorithm starts at nodechooses that node or vertex as its root nodeand visits the neighboring nodesafter which it explores neighbors on the next level of the graph consider the following diagram as graphthe diagram is an example of an undirected graph we continue to use this type of graph to help make explanation easy without being too verbose the adjacency list for the graph is as followsgraph dict(graph[' '[' '' '' 'graph[' '[' '' '' 'graph[' '[' '' 'graph[' '[' '' 'graph[' '[' '' 'graph[' '[' '' '' 'graph[' '[' '' 'graph[' '[' 'in trying to traverse this graph breadth firstwe will employ the use of queue the algorithm creates list to store the nodes that have been visited as the traversal process proceeds we shall start our traversal from node
13,660
node is queued and added to the list of visited nodes afterwardwe use while loop to effect traversal of the graph in the while loopnode is dequeued its unvisited adjacent nodes bgand are sorted in alphabetical order and queued up the queue will now contain the nodes bdand these nodes are also added to the list of visited nodes at this pointwe start another iteration of the while loop because the queue is not emptywhich also means we are not really done with the traversal node is dequeued out of its adjacent nodes afand enode has already been visited thereforewe only enqueue the nodes and in alphabetical order nodes and are then added to the list of visited nodes our queue now holds the following nodes at this pointdgeand the list of visited nodes contains abdgef node is dequeued but all of its adjacent nodes have been visited so we simply dequeue it the next node at the front of the queue is we dequeue node but we also find out that all its adjacent nodes have been visited because they are in the list of visited nodes node is also dequeued we dequeue node too because all of its nodes have been visited the only node in the queue now is node node is dequeued and we realize that out of its adjacent nodes bdand conly node has not been visited we then enqueue node and add it to the list of visited nodes node is dequeued node has the adjacent nodes and but has already been visitedleaving node node is enqueued and added to the list of visited nodes finallythe last iteration of the while loop will lead to node being dequeued its only adjacent node has already been visited once the queue is completely emptythe loop breaks the output of the traversing the graph in the diagram is abdgefch the code for breadth-first search is given as followsfrom collections import deque def breadth_first_search(graphroot)visited_vertices list(graph_queue deque([root]visited_vertices append(rootnode root while len(graph_queue node graph_queue popleft(adj_nodes graph[node
13,661
remaining_elements set(adj_nodesdifference(set(visited_vertices)if len(remaining_elements for elem in sorted(remaining_elements)visited_vertices append(elemgraph_queue append(elemreturn visited_vertices when we want to find out whether set of nodes are in the list of visited nodeswe use the statement remaining_elements set(adj_nodesdifference(set(visited_vertices)this uses the set object' difference method to find the nodes that are in adj_nodes but not in visited_vertices in the worst-case scenarioeach vertex or node and edge will be traversedthus the time complexity of the algorithm is (| | |)where |vis the number of vertices or nodes while |eis the number of edges in the graph depth-first search as the name suggeststhis algorithm traverses the depth of any particular path in the graph before traversing its breadth as suchchild nodes are visited first before sibling nodes it works on finite graphs and requires the use of stack to maintain the state of the algorithmdef depth_first_search(graphroot)visited_vertices list(graph_stack list(graph_stack append(rootnode root the algorithm begins by creating list to store the visited nodes the graph_stack stack variable is used to aid the traversal process for continuity' sakewe are using regular python list as stack the starting nodecalled rootis passed with the graph' adjacency matrixgraph root is pushed onto the stack node root holds the first node in the stackwhile len(graph_stack if node not in visited_verticesvisited_vertices append(node
13,662
adj_nodes graph[nodeif set(adj_nodesissubset(set(visited_vertices))graph_stack pop(if len(graph_stack node graph_stack[- continue elseremaining_elements set(adj_nodesdifference(set(visited_vertices)first_adj_node sorted(remaining_elements)[ graph_stack append(first_adj_nodenode first_adj_node return visited_vertices the body of the while loop will be executed provided the stack is not empty if node is not in the list of visited nodeswe add it all adjacent nodes to node are collected by adj_nodes graph[nodeif all the adjacent nodes have been visitedwe pop that node from the stack and set node to graph_stack[- graph_stack[- is the top node on the stack the continue statement jumps back to the beginning of the while loop' test condition ifon the other handnot all the adjacent nodes have been visitedthe nodes that are yet to be visited are obtained by finding the difference between the adj_nodes and visited_vertices with the statement remaining_elements set(adj_nodesdifference(set(visited_vertices)the first item within sorted(remaining_elementsis assigned to first_adj_nodeand pushed onto the stack we then point the top of the stack to this node when the while loop existswe will return the visited_vertices
13,663
dry running the algorithm will prove useful consider the following graphthe adjacency list of such graph is given as followsgraph dict(graph[' '[' '' 'graph[' '[' 'graph[' '[' ',' ',' 'graph[' '[' 'graph[' '[' ',' ',' 'graph[' '[' ',' 'graph[' '[' ',' 'graph[' '[' ',' 'graph[' '[' ',' ',' ',' 'node is chosen as our beginning node node is pushed onto the stack and added to the visisted_vertices list in doing sowe mark it as having been visited the stack graph_stack is implemented with simple python list our stack now has as its only element we examine node ' adjacent nodes and to test whether all the adjacent nodes of have been visitedwe use the if statementif set(adj_nodesissubset(set(visited_vertices))graph_stack pop(if len(graph_stack node graph_stack[- continue
13,664
if all the nodes have been visitedwe pop the top of the stack if the stack graph_stack is not emptywe assign the node on top of the stack to node and start the beginning of another execution of the body of the while loop the statement set(adj_nodesissubset(set(visited_vertices)will evaluate to true if all the nodes in adj_nodes are subset of visited_vertices if the if statement failsit means that some nodes remain to be visited we obtain that list of nodes with remaining_elements set(adj_nodesdifference(set(visited_vertices)from the diagramnodes and will be stored in remaining_elements we will access the list in alphabetical orderfirst_adj_node sorted(remaining_elements)[ graph_stack append(first_adj_nodenode first_adj_node we sort remaining_elements and return the first node to first_adj_node this will return we push node onto the stack by appending it to the graph_stack we prepare node for access by assigning it to node on the next iteration of the while loopwe add node to the list of visited nodes we discover that the only adjacent node to bwhich is ahas already been visited because all the adjacent nodes of have been visitedwe pop it off the stackleaving node as the only element on the stack we return to node and examine whether all of its adjacent nodes have been visited the node now has as the only unvisited node we push to the stack and begin the whole process again the output of the traversal is - - - - - - - - depth-first searches find application in solving maze problemsfinding connected componentsand finding the bridges of graphamong others other useful graph methods very oftenyou are concerned with finding path between two nodes you may also want to find all the paths between nodes another useful method would be to find the shortest path between nodes in an unweighted graphthis would simply be the path with the lowest number of edges between them in weighted graphas you have seenthis could involve calculating the total weight of passing through set of edges of coursein different situationyou may want to find the longest or shortest path
13,665
priority queues and heaps priority queue is basically type of queue that will always return items in order of priority this priority could befor examplethat the lowest item is always popped off first although it is called queuepriority queues are often implemented using heapsince it is very efficient for this purpose consider thatin storecustomers queue in line where service is only rendered at the front of the queue each customer will spend some time in the queue to get served if the waiting times for the customers in the queue are and then the average time spent in the queue becomes ( )/ which is howeverif we change the order of service such that customers with the least amount of waiting time are served firstthen we obtain different average waiting time in doing sowe calculate our new average waiting time by ( )/ which now equals better average waiting time clearlythere is merit to serving the customers from the least waiting time upward this method of selecting the next item by priority or some other criterion is the basis for creating priority queues heap is data structure that satisfies the heap property the heap property states that there must be certain relationship between parent node and its child nodes this property must apply through the entire heap in min heapthe relationship between parent and children is that the parent must always be less than or equal to its children as consequence of thisthe lowest element in the heap must be the root node in max heapon the other handthe parent is greater than or equal to its child or its children it follows from this that the largest value makes up the root node as you can see from what we just mentionedheaps are trees andto be more specificbinary trees although we are going to use binary treewe will actually use list to represent it this is possible because the heap will store complete binary tree complete binary tree is one in which each row must be fully filled before starting to fill the next row
13,666
to make the math with indexes easierwe are going to leave the first item in the list (index empty after thatwe place the tree nodes into the listfrom top to bottomleft to rightif you observe carefullyyou will notice that you can retrieve the children of any node very easily the left child is located at and the right child is located at this will always hold true
13,667
we are going to look at min heap implementation it shouldn' be difficult to reverse the logic in order to get max heapclass heapdef __init__(self)self heap [ self size we initialize our heap list with zero to represent the dummy first element (remember that we are only doing this to make the math simplerwe also create variable to hold the size of the heap this would not be necessary as suchsince we could check the size of the listbut we would always have to remember to reduce it by one so we chose to keep separate variable instead inserting inserting an item is very simple in itself we add the new element to the end of the list (which we understand to be the bottom of the treethen we increment the size of the heap by one but after each insertwe need to float the new element up if needed bear in mind that the lowest element in the min heap needs to be the root element we first create helper method called float that takes care of this let us look at how it is meant to behave imagine that we have the following heap and want to insert the value the new element has occupied the last slot in the third row or level its index value is now we compare that value with its parent the parent is at index / (integer divisionthat element holds so we swap the
13,668
our new element has been swapped and moved up to index we have not reached the top of the heap yet ( )so we continue the new parent of our element is at index / so we compare andif necessaryswap againafter the final swapwe are left with the heap looking as follows notice how it adheres to the definition of heap
13,669
here follows an implementation of what we have just describeddef float(selfk)we are going to loop until we have reached the root node so that we can keep floating the element up as high as it needs to go since we are using integer divisionas soon as we get below the loop will break outwhile / compare parent and child if the parent is greater than the childswap the two valuesif self heap[kself heap[ // ]self heap[ ]self heap[ // self heap[ // ]self heap[kfinallylet' not forget to move up the treek // this method ensures that the elements are ordered properly now we just need to call this from our insert methoddef insert(selfitem)self heap append(itemself size + self float(self sizenotice the last line in insert calls the float(method to reorganize the heap as necessary pop just like insertpop(is by itself simple operation we remove the root node and decrement the size of the heap by one howeveronce the root has been popped offwe need new root node to make this as simple as possiblewe just take the last item in the list and make it the new root that iswe move it to the beginning of the list but now we might not have the lowest element at the top of the heapso we perform the opposite of the float operationwe let the new root node sink down as required
13,670
as we did with insertlet us have look at how the whole operation is meant to work on an existing heap imagine the following heap we pop off the root elementleaving the heap temporarily rootlesssince we cannot have rootless heapwe need to fill this slot with something if we choose to move up one of the childrenwe will have to figure out how to rebalance the entire tree structure so insteadwe do something really interesting we move up the very last element in the list to fill the position of the root elementnow this element clearly is not the lowest in the heap this is where we begin to sink it down first we need to determine where to sink it down we compare the two childrenso that the lowest element will be the one to float up as the root sinks down
13,671
the right child is clearly less its index is which represents the root index we go ahead and compare our new root node with the value at this indexnow our node has jumped down to index we need to compare it to the lesser of its children howevernow we only have one childso we don' need to worry about which child to compare against (for min heapit is always the lesser child)there is no need to swap here since there are no more rows eitherwe are done notice again howafter the sink(operation is completedour heap adheres to the definition of heap now we can begin implementing this before we do the sink(method itselfnotice how we need to determine which of the children to compare our parent node against welllet us put that selection in its own little methodjust to make the code look little simplerdef minindex(selfk)we may get beyond the end of the listin which case we return the index of the left childif self sizereturn
13,672
otherwisewe simply return the index of the lesser of the two childrenelif self heap[ * self heap[ * + ]return elsereturn now we can create the sink functiondef sink(selfk)as beforewe are going to loop so that we can sink our element down as far as is neededwhile <self sizenext we need to know which of the left or the right child to compare against this is where we make use of the minindex(functionmi self minindex(kas we did in the float(methodwe compare parent and child to see whether we need to swapif self heap[kself heap[mi]self heap[ ]self heap[miself heap[mi]self heap[kand we need to make sure that we move down the tree so that we don' get stuck in loopk mi the only thing remaining now is to implement pop(itself this is very straightforward as the grunt work is performed by the sink(methoddef pop(self)item self heap[ self heap[ self heap[self sizeself size - self heap pop(self sink( return item
13,673
testing the heap now we just need some code to test the heap we begin by creating our heap and inserting some datah heap(for in ( ) insert(iwe can print the heap listjust to inspect how the elements are ordered if you redraw this as tree structureyou should notice that it meets the required properties of heapprint( heapnow we will pop off the itemsone at time notice how the items come out in sorted orderfrom lowest to highest also notice how the heap list changes after each pop it is good idea to take out pen and paper and to redraw this list as tree after each popto fully understand how the sink(method worksfor in range( ) pop(print(nprint( heapin the on sorting algorithmswe will reorganize the code for the heap sort algorithm once you have the min heap working properly and understand how it worksit should be simple task to implement max heap all you have to do is to reverse the logic selection algorithms selection algorithms fall under class of algorithms that seek to answer the problem of finding the ith-smallest element in list when list is sorted in ascending orderthe first element in the list will be the smallest item in the list the second element in the list will be the second-smallest element in the list the last element in the list will be the last-smallest element in the list but that will also qualify as the largest element in the list
13,674
in creating the heap data structurewe have come to the understanding that call to the pop method will return the smallest element in the heap the first element to pop off min heap is the first-smallest element in the list similarlythe seventh element to be popped off the min heap will be the seventh-smallest element in the list thereforeto find the ithsmallest element in list will require us to pop the heap number of times that is very simple and efficient way of finding the ith-smallest element in list but in selection algorithmswe will study another approach by which we can find the ith-smallest element in list selection algorithms have applications in filtering out noisy datafinding the mediansmallestand largest elements in listand can even be applied in computer chess programs summary graphs and heaps have been treated in this we looked at ways to represent graph in python using lists and dictionaries in order to traverse the graphwe looked at breadth-first searches and depth-first searches we then switched our attention to heaps and priority queues to understand their implementation the ended with using the concept of heap to find the ith-smallest element in list the subject of graphs is very complicated and just one will not do justice to it the journey with nodes will end with this the next will usher us into the arena of searching and the various means by which we can efficiently search for items in lists
13,675
searching with the data structures that have been developed in the preceding one critical operation performed on all of them is searching in this we shall explore the different strategies that can be used to find elements in collection of items one other important operation that makes use of searching is sorting it is virtually impossible to sort without some variant of search operation the "how of searchingis also important as it has bearing on how quick sorting algorithm ends up performing searching algorithms are categorized under two broad types one category assumes that the list of items to apply the searching operation onhas already been sorted whiles the other does not the performance of search operation is heavily influenced by whether the items about to be searched have already been sorted or not as we will see in the subsequent topics too linear search let us focus our discussions on linear searchperformed on typical python list
13,676
the preceding list has elements that are accessible through the list index to find an element in the list we employ the linear searching technique this technique traverses the list of elementsby using the index to move from the beginning of the list to the end each element is examined and if it does not match the search itemthe next item is examined by hopping from one item to its nextthe list is traversed sequentially in treating the sections in this and otherswe use list with integers to enhance our understanding since integers lend themselves to easy comparison unordered linear search list containing elements and is an example of an unordered list the items in the list have no order by magnitude to perform search operation on such listone proceeds from the very first itemcompares that with the search item if match is not made the next element in the list is examined this continues till we reach the last element in the list or until match is made def search(unordered_listterm)unordered_list_size len(unordered_listfor in range(unordered_list_size)if term =unordered_list[ ]return return none the search function takes as parametersthe list that houses our data and the item that we are looking for called the search term the size of the array is obtained and determines the number of times the for loop is executed if term =unordered_list[ ]on every pass of the for loopwe test if the search term is equal to the item that the index points to if truethen there is no need to proceed with the search we return the position where the match occurred if the loop runs to the end of the list with no match being madenone is returned to signify that there is no such item in the list
13,677
in an unordered list of itemsthere is no guiding rule for how elements are inserted this therefore impacts the way the search is done the lack of order means that we cannot rely on any rule to perform the search as suchwe must visit the items in the list one after the other as can be seen in the following imagethe search for the term starts from the first element and moves to next element in the list thus compared with and if it is not equalwe compare with and so on till we find the search term in the list the unordered linear search has worst case running time of (nall the elements may need to be visited before finding the search term this will be the case if the search term is located at the last position of the list ordered linear search in the case where the elements of list have been already sortedour search algorithm can be improved assuming the elements have been sorted in ascending orderthe search operation can take advantage of the ordered nature of the list to make search more efficient the algorithm is reduced to the following steps move through the list sequentially if search item is greater than the object or item currently under inspection in the loopthen quit and return none
13,678
in the process of iterating through the listif the search term is greater than the current itemthen there is no need to continue with the search when the search operation starts and the first element is compared with ( )no match is made but because there are more elements in the list the search operation moves on to examine the next element more compelling reason to move on is that we know the search item may match any of the elements greater than after the th comparisonwe come to the conclusion that the search termcan not be found in any position above where is located in other wordsif the current item is greater than the search termthen it means there is no need to further search the list def search(ordered_listterm)ordered_list_size len(ordered_listfor in range(ordered_list_size)if term =ordered_list[ ]return elif ordered_list[itermreturn none return none the if statement now caters for this check the elif portion tests the condition where ordered_list[iterm the method returns none if the comparison evaluates to true the last line in the method returns none because the loop may go through the list and still not find any element matching the search term
13,679
the worst case time complexity of an ordered linear search is (nin generalthis kind of search is considered inefficient especially when dealing with large data sets binary search binary search is search strategy used to find elements within list by consistently reducing the amount of data to be searched and thereby increasing the rate at which the search term is found to use binary search algorithmthe list to be operated on must have already been sorted the binary term carries number of meanings and helps us put our minds in the right frame to understand the algorithm binary decision has to be made at each attempt to find an item in the list one critical decision is to guess which part of the list is likely to house the item we are looking for would the search term be in the first half of second half of the listthat isif we always perceive the list as being comprised of two partsinstead of moving from one cell of the list to the otherif we employ the use of an educated guessing strategywe are likely to arrive at the position where the item will be found much faster as an examplelets take it that we want to find the middle page of page book we already know that every book has its pages numbered sequentially from upwards so it figures that the th page should be found right at the middle of the bookinstead of moving and flipping from page to reach the th page let' say we decide to now look for the page we can still use our strategy to find the page easily we guess that page cuts the book in half page will lay to the left of the book no need to worry about whether we can find th page between page and because it can never be found there so using page as referencewe can open to about half of the pages that lay between the st and th page that brings us closer to finding the th page the following is the algorithm for conducting binary search on an ordered list of itemsdef binary_search(ordered_listterm)size_of_list len(ordered_list index_of_first_element index_of_last_element size_of_list while index_of_first_element <index_of_last_element
13,680
mid_point (index_of_first_element index_of_last_element)/ if ordered_list[mid_point=termreturn mid_point if term ordered_list[mid_point]index_of_first_element mid_point elseindex_of_last_element mid_point if index_of_first_element index_of_last_elementreturn none let' assume we have to find the position where the item is located in the list as followsthe algorithm uses while loop to iteratively adjust the limits in the list within which to find search term so far as the difference between the starting indexindex_of_first_element and the index_of_last_element index is positivethe while loop will run the algorithm first finds the mid point of the list by adding the index of the first element ( to that of the last ( and dividing it by to find the middle indexmid_point mid_point (index_of_first_element index_of_last_element)/ in this case is not found at the middle position or index in the list if we were searching for we would have had to adjust the index_of_first_element to mid_point + but because lies on the other side of the listwe adjust index_of_last_element to mid_point-
13,681
with our new index of index_of_first_element and index_of_last_element now being and respectivelywe compute the mid ( )/ which equals the new midpoint is we find the middle item and compare with the search itemordered_list[ which yields the value voilaour search term is found this reduction of our list size by halfby re-adjusting the index of the index_of_first_element and index_of_last_element continues as long as index_of_first_element is less than index_of_last_element when this fails to be the case it is most likely that our search term is not in the list the implementation here is an iterative one we can also develop recursive variant of the algorithm by applying the same principle of shifting the pointers that mark the beginning and ending of the search list def binary_search(ordered_listfirst_element_indexlast_element_indexterm)if (last_element_index first_element_index)return none elsemid_point first_element_index ((last_element_index first_element_index if ordered_list[mid_pointtermreturn binary_search(ordered_listfirst_element_indexmid_point- ,termelif ordered_list[mid_pointtermreturn binary_search(ordered_listmid_point+ last_element_indextermelsereturn mid_point
13,682
call to this recursive implementation of the binary search algorithm and its output is as followsstore [ print(binary_search(store )output> there only distinction between the recursive binary search and the iterative binary search is the function definition and also the way in which mid_point is calculated the calculation for the mid_point after the ((last_element_index first_element_index operation must add its result to first_element_index that way we define the portion of the list to attempt the search the binary search algorithm has worst time complexity of (log nthe half-ing of the list on each iteration follows log of the number of elements progression it goes without saying that in log is assumed to be referring to log base interpolation search there is another variant of the binary search algorithm that may closely be said to mimic morehow humans perform search on any list of items it is still based off trying to make good guess of where in sorted list of itemsa search item is likely to be found examine the following list of items for exampleto find we know to look at the right hand portion of the list our initial treatment of binary search would typically examine the middle element first in order to determine if it matches the search term
13,683
more human thing would be to pick middle element in such way as to not only split the array in half but to get as close as possible to the search term the middle position was calculated for using the following rulemid_point (index_of_first_element index_of_last_element)/ we shall replace this formula with better one that brings us close to the search term mid_point will receive the return value of the nearest_mid function def nearest_mid(input_listlower_bound_indexupper_bound_indexsearch_value)return lower_bound_index (upper_bound_index -lower_bound_index)(input_list[upper_bound_index-input_list[lower_bound_index])(search_value -input_list[lower_bound_index]the nearest_mid function takes as argumentsthe list on which to perform the search the lower_bound_index and upper_bound_index parameters represent the bounds in the list within which we are hoping to find the search term search_value represents the value being searched for these are used in the formulalower_bound_index (upper_bound_index lower_bound_index)(input_list[upper_bound_indexinput_list[lower_bound_index])(search_value input_list[lower_bound_index]given our search list and the nearest_mid will be computed with the following valueslower_bound_index upper_bound_index input_list[upper_bound_index input_list[lower_bound_index search_value it can now be seen thatthe mid_point will receive the value which is the index of the location of our search term binary search would have chosen as the mid which will require another run of the algorithm
13,684
more visual illustration of how typical binary search differs from an interpolation is given as follows for typical binary search finds the midpoint like soone can see that the midpoint is actually standing approximately in the middle of the preceding list this is as result of dividing by list an interpolation search on the other hand would move like soin interpolation searchour midpoint is swayed more to the left or right this is caused by the effect of the multiplier used when dividing to obtain the midpoint from the preceding imageour midpoint has been skewed to the right the remainder of the interpolation algorithm remains the same as that of the binary search except for the way the mid position is calculated for def interpolation_search(ordered_listterm)size_of_list len(ordered_list index_of_first_element index_of_last_element size_of_list while index_of_first_element <index_of_last_element
13,685
mid_point nearest_mid(ordered_listindex_of_first_elementindex_of_last_elementtermif mid_point index_of_last_element or mid_point index_of_first_elementreturn none if ordered_list[mid_point=termreturn mid_point if term ordered_list[mid_point]index_of_first_element mid_point elseindex_of_last_element mid_point if index_of_first_element index_of_last_elementreturn none the nearest_mid function makes use of multiplication operation this can produce values that are greater than the upper_bound_index or lower than the lower_bound_index when this occursit means the search termtermis not in the list none is therefore returned to represent this so what happens when ordered_list[mid_pointdoes not equal the search themwellwe must now re-adjust the index_of_first_element and index_of_last_element such that the algorithm will focus on the part of the array that is likely to contain the search term this is like exactly what we did in the binary search if term ordered_list[mid_point]index_of_first_element mid_point if the search term is greater than the value stored at ordered_list[mid_point]then we only adjust the index_of_first_element variable to point to the index mid_point
13,686
the following image shows how the adjustment occurs the index_of_first_element is adjusted and pointed to the index of mid_point+ the image only illustrates the adjustment of the midpoint in interpolation rarely does the midpoint divide the list in equal halves on the other handif the search term is lesser than the value stored at ordered_list[mid_point]then we only adjust the index_of_last_element variable to point to the index mid_point this logic is captured in the else part of the if statement index_of_last_element mid_point the image shows the effect of the recalculation of index_of_last_element on the position of the midpoint let' use more practical example to understand the inner workings of both the binary search and interpolation algorithms
13,687
take the list with elements at index is stored and at index is found the value nowassume that we want to find the element in the list how will the two different algorithms go about itif we pass this list to the interpolation search functionthe nearest_mid function will return value equal to just by one comparisonwe would have found the search term on the other handthe binary search algorithm would need three comparisons to arrive at the search term as illustrated in the following imagethe first mid_point calculated is the second mid_point is and the last mid_point where the search term is found is choosing search algorithm the binary search and interpolation search operations are better in performance than both ordered and unordered linear search functions because of the sequential probing of elements in the list to find the search termordered and unordered linear search have time complexity of (nthis gives very poor performance when the list is large the binary search operation on the other handslices the list in twoanytime search is attempted on each iterationwe approach the search term much faster than in linear strategy the time complexity yields (log ndespite the speed gain in using binary searchit is most it can not be used on an unsorted list of items neither is it advised to be used for list of small sizes
13,688
the ability to get to the portion of the list that houses search term determines to large extenthow well search algorithm will perform in the interpolation search algorithmthe mid is calculated for which gives higher probability of obtaining our search term the time complexity of the interpolation search is olog log )this gives rise to faster search compared to its variantbinary search summary in this we have examined two breeds of search algorithms the implementation of both linear and binary search algorithms have been discussed and their comparisons drawn the binary search variantinterpolation search has also been treated in this section knowing which kind of search operation to use will be relevant in subsequent in our next we shall use the knowledge that we have gained to enable us perform sorting operations on list of items
13,689
sorting whenever data is collectedthere comes time when it becomes necessary to sort the data the sorting operation is common to all datasetsbe it collection of namestelephone numbersor items on simple to-do list in this we'll study few sorting techniquesincluding the followingbubble sort insertion sort selection sort quick sort heap sort in our treatment of these sorting algorithmswe will take into consideration their asymptotic behavior some of the algorithms are relatively easy to develop but may perform poorly other algorithms that are little complex to write will show impressive performance after sortingit becomes much easier to conduct search operations on collection of items we'll start with the simplest of all sorting algorithms--the bubble sort algorithm sorting algorithms in this we will go through number of sorting algorithms that have varying levels of difficulty of implementation sorting algorithms are categorized by their memory usagecomplexityrecursionwhether they are comparison-based among other considerations
13,690
some of the algorithms use more cpu cycles and as such have bad asymptotic values others chew on more memory and other computing resources as they sort number of values another consideration is how sorting algorithms lend themselves to being expressed recursively or iteratively or both there are algorithms that use comparison as the basis for sorting elements an example of this is the bubble sort algorithm examples of non-comparison sorting algorithm are the buck sort and pigeonhole sort bubble sort the idea behind bubble sort algorithm is very simple given an unordered listwe compare adjacent elements in the listeach timeputting in the right order of magnitudeonly two elements the algorithm hinges on swap procedure take list with only two elementsto sort this listsimply swap them into the right position with occupying index and occupying index to effectively swap these elementswe need to have temporary storage area
13,691
implementation of the bubble sort algorithm starts with the swap methodillustrated in the preceding image firstelement will be copied to temporary locationtemp then element will be moved to index finally will be moved from temp to index at the end of it allthe elements will have been swapped the list will now contain the element[ the following code will swap the elements of unordered_list[jwith unordered_list[ + if they are not in the right ordertemp unordered_list[junordered_list[junordered_list[ + unordered_list[ + temp now that we have been able to swap two-element arrayit should be simple to use this same idea to sort whole list we'll run this swap operation in double-nested loop the inner loop is as followsfor in range(iteration_number)if unordered_list[junordered_list[ + ]temp unordered_list[junordered_list[junordered_list[ + unordered_list[ + temp knowing how many times to swap is important when implementing bubble sort algorithm to sort list of numbers such as [ ]we need to swap the elements maximum of twice this is equal to the length of the list minus iteration_number len(unordered_list)- we subtract because it gives us exactly the maximum number of iterations to run
13,692
by swapping the adjacent elements in exactly two iterationsthe largest number ends up at the last position on the list the if statement makes sure that no needless swaps occur if two adjacent elements are already in the right order the inner for loop only causes the swapping of adjacent elements to occur exactly twice in our list howeveryou'll realize that the running of the for loop for the first time does not entirely sort our list how many times does this swapping operation have to occur in order for the entire list to be sortedif we repeat the whole process of swapping the adjacent elements number of timesthe list will be sorted an outer loop is used to make this happen the swapping of elements in the list results in the following dynamicswe recognize that total of four comparisons at most were needed to get our list sorted thereforeboth inner and outer loops have to run len(unordered_list)- times for all elements to be sortediteration_number len(unordered_list)- for in range(iteration_number)for in range(iteration_number)if unordered_list[junordered_list[ + ]temp unordered_list[junordered_list[junordered_list[ + unordered_list[ + temp
13,693
the same principle is used even if the list contains many elements there are lot of variations of the bubble sort too that minimize the number of iterations and comparisons the bubble sort is highly inefficient sorting algorithm with time complexity of ( and best case of (ngenerallythe bubble sort algorithm should not be used to sort large lists howeveron relatively small listsit performs fairly well there is variant of the bubble sort algorithm where if there is no comparison within the inner loopwe simply quit the entire sorting process the absence of the need to swap elements in the inner loop suggests the list has already been sorted in waythis can help speed up the generally considered slow algorithm insertion sort the idea of swapping adjacent elements to sort list of items can also be used to implement the insertion sort in the insertion sort algorithmwe assume that certain portion of the list has already been sortedwhile the other portion remains unsorted with this assumptionwe move through the unsorted portion of the listpicking one element at time with this elementwe go through the sorted portion of the list and insert it in the right order so that the sorted portion of the list remains sorted that is lot of grammar let' walk through the explanation with an example consider the following array
13,694
the algorithm starts by using for loop to run between the indexes and we start from index because we assume the sub-array with index to already be in the sorted orderat the start of the execution of the loopwe have the followingfor index in range( len(unsorted_list))search_index index insert_value unsorted_list[indexat the beginning of the execution of each run of the for loopthe element at unsorted_list[indexis stored in the insert_value variable laterwhen we find the appropriate position in the sorted portion of the listinsert_value will be stored at that index or locationfor index in range( len(unsorted_list))search_index index insert_value unsorted_list[indexwhile search_index and unsorted_list[search_index- insert_value unsorted_list[search_indexunsorted_list[search_index- search_index - unsorted_list[search_indexinsert_value the search_index is used to provide information to the while loop--exactly where to find the next element that needs to be inserted in the sorted portion of the list
13,695
the while loop traverses the list backwardsguided by two conditionsfirstif search_index then it means that there are more elements in the sorted portion of the listsecondfor the while loop to rununsorted_list[search_index- must be greater than the insert_value the unsorted_list[search_index- array will do either of the following thingspoint to the element just before the unsorted_list[search_indexbefore the while loop is executed the first time point to one element before unsorted_list[search_index- after the while loop has been run the first time in our list examplethe while loop will be executed because in the body of the while loopthe element at unsorted_list[search_index- is stored at unsorted_list[search_indexsearch_index - moves the list traversal backwards till it bears the value our list now looks like thisafter the while loop exitsthe last known position of search_index (which in this case is now helps us to know where to insert insert_value
13,696
on the second iteration of the for loopsearch_index will have the value which is the index of the third element in the array at this pointwe start our comparison in the direction to the left (towards index will be compared with but because is greater than the while loop will not be executed will be replaced by itself because the search_index variable never got decremented as suchunsorted_list[search_indexinsert_value will have no effect when search_index is pointing at index we compare with and move to where is stored we then compare with and move to where was initially stored at this pointthe while loop will break and will be stored in index the array will be partially sorted with the values [ the preceding step will occur one last time for the list to be sorted the insertion sort algorithm is considered stable in that it does not change the relative order of elements that have equal keys it also only requires no more memory than what is consumed by the list because it does the swapping in-place its worst case value is ( and its best case is (nselection sort another popular sorting algorithm is the selection sort this sorting algorithm is simple to understandyet also inefficientwith its worst and best asymptotic values being ( it begins by finding the smallest element in an array and interchanging it with data atfor instancearray index [ the same operation is done second timehoweverthe smallest element in the remainder of the list after finding the first smallest element is interchanged with the data at index [ in bid to throw more light on how the algorithm workslets sort list of numbersstarting at index we search for the smallest item in the list that exists between index and the index of the last element when this element has been foundit is exchanged with the data found at index we simply repeat this process until the list becomes sorted
13,697
searching for the smallest item within the list is an incremental processa comparison of elements and selects as the lesser of the two the two elements are swapped after the swap operationthe array looks like thisstill at index we compare with since is greater than the two elements are not swapped further comparison is made between the element at index which is with element at index which is no swap takes place when we get to the last element in the listwe will have the smallest element occupying index new set of comparisons will beginbut this timefrom index we repeat the whole process of comparing the element stored there with all the elements between index through to the last index
13,698
the first step of the second iteration will look like thisthe following is an implementation of the selection sort algorithm the argument to the function is the unsorted list of items we want to put in ascending order of magnitudedef selection_sort(unsorted_list)size_of_list len(unsorted_listfor in range(size_of_list)for in range( + size_of_list)if unsorted_list[junsorted_list[ ]temp unsorted_list[iunsorted_list[iunsorted_list[junsorted_list[jtemp the algorithm begins by using the outer for loop to go through the listsize_of_lista number of times because we pass size_of_list to the range methodit will produce sequence from through to size_of_list- it is subtle note the inner loop is responsible for going through the list and making the necessary swap any time that we encounter an element less than the element pointed to by unsorted_list[inotice that the inner loop begins from + up to size_of_list- the inner loop begins its search for the smallest element between + but uses the index
13,699
the preceding diagram shows the direction in which the algorithm searches for the next smallest item quick sort the quick sort algorithm falls under the divide and conquer class of algorithmswhere we break (dividea problem into smaller chunks that are much simpler to solve (conquerin this casean unsorted array is broken into sub-arrays that are partially sorteduntil all elements in the list are in the right positionby which time our unsorted list will have become sorted list partitioning before we divide the list into smaller chunkswe have to partition it this is the heart of the quick sort algorithm to partition the arraywe must first select pivot all the elements in the array will be compared with this pivot at the end of the partitioning processall elements that are less than the pivot will be to the left of the pivotwhile all elements greater than the pivot will lie to the right of the pivot in the array pivot selection for the sake of simplicitywe'll take the first element in any array as the pivot this kind of pivot selection degrades in performanceespecially when sorting an already sorted list randomly picking the middle or last element in the array as the pivot does not improve the situation any further in the next we will adopt better approach to selecting the pivot in order to help us find the smallest element in list implementation before we delve into the codelet' run through the sorting of list using the quick sort algorithm the partitioning step is very important to understand so we'll tackle that operation first