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 l... |
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 als... |
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 retu... |
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 ... |
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 ... |
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 ... |
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... |
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 cod... |
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 ... |
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... |
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 pl... |
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... |
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 n... |
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 ... |
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 downwards... |
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 no... |
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 no... |
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 shal... |
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 ar... |
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 ... |
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 valu... |
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 wi... |
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 numbersth... |
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 curr... |
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 o... |
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 i... |
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 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 ne... |
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 sel... |
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 b... |
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 nodei... |
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 an... |
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 rig... |
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 ... |
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 postf... |
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 ... |
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... |
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 bina... |
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 nu... |
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 th... |
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 fol... |
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 acces... |
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 ta... |
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 tab... |
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 dividi... |
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 t... |
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 ... |
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 addressi... |
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 chainin... |
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 w... |
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... |
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 ... |
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 ... |
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 th... |
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... |
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 ... |
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 m... |
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 th... |
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 visit... |
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... |
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 th... |
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 beg... |
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 ... |
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 c... |
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 ch... |
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 ... |
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 i... |
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 h... |
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 comp... |
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 r... |
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( hea... |
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... |
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 ... |
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 searc... |
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 sear... |
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 ex... |
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 inc... |
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 ... |
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 r... |
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 calculat... |
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 th... |
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 o... |
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_o... |
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 val... |
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 wou... |
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 )t... |
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 ... |
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 com... |
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 t... |
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 ... |
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 ... |
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... |
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... |
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 b... |
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... |
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)f... |
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 broke... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.