id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
21,600 | sub-tree with root has height and sub-tree with root has height insertion as with the red-black treeinsertion is somewhat complex and involves number of cases implementations of avl tree insertion may be found in many textbooksthey rely on adding an extra attributethe balance factor to each node this factor indicates w... |
21,601 | +-tree in +-treeeach node stores up to references to children and up to keys each reference is considered "betweentwo of the node' keysit references the root of subtree for which all values are between these two keys here is fairly small tree using as our value for +-tree requires that each leaf be the same distance fr... |
21,602 | each leaf contains at least floor( keys every key from the table appears in leafin left-to-right sorted order in our exampleswe'll continue to use for looking at our invariantsthis requires that each leaf have at least two keysand each internal node to have at least two children (and thus at least one key insertion alg... |
21,603 | insert insert insert deletion algorithm descend to the leaf where the key exists remove the required key and associated reference from the node if the node still has enough keys and references to satisfy the invariantsstop |
21,604 | youngest sibling at the same level has more than necessarydistribute the keys between this node and the neighbor repair the keys in the level above to represent that these nodes now have different "split pointbetween themthis involves simply changing key in the levels abovewithout deletion or insertion if the node has ... |
21,605 | delete expression treestrees are used in many other ways in the computer science compilers and database are two major examples in this regard in case of compilerswhen the languages are translated into machine languagetree-like structures are used we have also seen an example of expression tree comprising the mathematic... |
21,606 | have if you look at the figureit becomes evident that the inner nodes contain operators while leaf nodes have operands we know that there are two types of nodes in the tree inner nodes and leaf nodes the leaf nodes are such nodes which have left and right subtrees as null you will find these at the bottom level of the ... |
21,607 | binary search tree (bsta binary search tree (bstis tree in which all the nodes follow the below-mentioned properties the left sub-tree of node has key less than or equal to its parent node' key the right sub-tree of node has key greater than to its parent node' key thusbst divides all its sub-trees into two segmentsthe... |
21,608 | struct node int datastruct node *leftchildstruct node *rightchild}search operation whenever an element is to be searchedstart searching from the root node then if the data is less than the key valuesearch for the element in the left subtree otherwisesearch for the element in the right subtree follow the same algorithm ... |
21,609 | return nullreturn currentinsert operation whenever an element is to be insertedfirst locate its proper location start searching from the root nodethen if the data is less than the key valuesearch for the empty location in the left subtree and insert the data otherwisesearch for the empty location in the right subtree a... |
21,610 | parent current//go to left of the tree if(data datacurrent current->leftchild//insert to the left if(current =nullparent->leftchild tempnodereturn//go to right of the tree else current current->rightchild//insert to the right if(current =nullparent->rightchild tempnodereturn |
21,611 | lecture- graphs terminology graph consists ofa setvof vertices (nodesa collectioneof pairs of vertices from called edges (arcsedgesalso called arcsare represented by (uvand are eitherdirected if the pairs are ordered (uvu the origin the destination undirected if the pairs are unordered graph is pictorial representation... |
21,612 | properties if graphghas edges then svg deg( if di-graphghas edges then svg indeg(vm svg outdeg(vif simple graphghas edges and verticesif is also directed then < ( - if is also undirected then < ( - )/ so simple graph with vertices has ( edges at most more terminology path is sequence of alternating vetches and edges su... |
21,613 | depth first searchdepth first search (dfsalgorithm traverses graph in depthward motion and uses stack to remember to get the next vertex to start searchwhen dead end occurs in any iteration as in the example given abovedfs algorithm traverses from to to to to to firstthen to and lastly to it employs the following rules... |
21,614 | mark as visited and put it onto the stack explore any unvisited adjacent node from we have three nodes and we can pick any of them for this examplewe shall take the node in an alphabetical order mark as visited and put it onto the stack explore any unvisited adjacent node from both sand are adjacent to but we are conce... |
21,615 | we check the stack top for return to the previous node and check if it has any unvisited nodes herewe find to be on the top of the stack only unvisited adjacent node is from is now so we visit cmark it as visited and put it onto the stack as does not have any unvisited adjacent node so we keep popping the stack until w... |
21,616 | breadth first search breadth first search (bfsalgorithm traverses graph in breadthward motion and uses queue to remember to get the next vertex to start searchwhen dead end occurs in any iteration as in the example given abovebfs algorithm traverses from to to to first then to and lastly to it employs the following rul... |
21,617 | we start from visiting (starting node)and mark it as visited we then see an unvisited adjacent node from in this examplewe have three nodes but alphabetically we choose amark it as visited and enqueue it nextthe unvisited adjacent node from is we mark it as visited and enqueue it nextthe unvisited adjacent node from is... |
21,618 | nows is left with no unvisited adjacent nodes sowe dequeue and find from we have as unvisited adjacent node we mark it as visited and enqueue it at this stagewe are left with no unmarked (unvisitednodes but as per the algorithm we keep on dequeuing in order to get all unvisited nodes when the queue gets emptiedthe prog... |
21,619 | graph representation you can represent graph in many ways the two most common ways of representing graph is as followsadjacency matrix an adjacency matrix is vxv binary matrix element ai, is if there is an edge from vertex to vertex else ai,jis notea binary matrix is matrix in which the cells can have only one of two p... |
21,620 | the other way to represent graph is by using an adjacency list an adjacency list is an array of separate lists each element of the array ai is listwhich contains all the vertices that are adjacent to vertex for weighted graphthe weight or cost of the edge is stored along with the vertex in the list using pairs in an un... |
21,621 | consider the same directed graph from an adjacency matrix the adjacency list of the graph is as followsa |
21,622 | topological sortingtopological sorting for directed acyclic graph (dagis linear ordering of vertices such that for every directed edge uvvertex comes before in the ordering topological sorting for graph is not possible if the graph is not dag for examplea topological sorting of the following graph is " there can be mor... |
21,623 | /| | \|( )>( note that the value of graph[ ][jis if is equal to and graph[ ][jis inf (infiniteif there is no edge from vertex to outputshortest distance matrix inf inf inf inf inf inf floyd warshall algorithm we initialize the solution matrix same as the input graph matrix as first step then we update the solution matr... |
21,624 | bubble sort we take an unsorted array for our example bubble sort takes ( time so we're keeping it short and precise bubble sort starts with very first two elementscomparing them to check which one is greater in this casevalue is greater than so it is already in sorted locations nextwe compare with we find that is smal... |
21,625 | and when there' no swap requiredbubble sorts learns that an array is completely sorted now we should look into some practical aspects of bubble sort algorithm we assume list is an array of elements we further assume that swapfunction swaps the values of the given array elements begin bubblesort(listfor all elements of ... |
21,626 | /compare the adjacent elements *if list[jlist[ + then /swap them *swaplist[ ]list[ + swapped true end if end for /*if no number was swapped that means array is sorted nowbreak the loop *if(not swappedthen break end if end for end procedure return list |
21,627 | insertion sort we take an unsorted array for our example insertion sort compares the first two elements it finds that both and are already in ascending order for now is in sorted sub-list insertion sort moves ahead and compares with and finds that is not in the correct position it swaps with it also checks with all the... |
21,628 | again we find and in an unsorted order we swap them again by the end of third iterationwe have sorted sub-list of items this process goes on until all the unsorted values are covered in sorted sub-list now we shall see some programming aspects of insertion sort algorithm now we have bigger picture of how this sorting t... |
21,629 | selection sort consider the following depicted array as an example for the first position in the sorted listthe whole list is scanned sequentially the first position where is stored presentlywe search the whole list and find that is the lowest value so we replace with after one iteration which happens to be the minimum... |
21,630 | algorithm step set min to location step search the minimum element in the list step swap with value at location min step increment min to point to next element step repeat until list is sorted |
21,631 | procedure selection sort list array of items size of list for to /set current element as minimum*min /check the element to be minimum *for + to if list[jlist[minthen min jend if end for /swap the minimum element with the current element*if indexmin ! then swap list[minand list[iend if end for end procedure |
21,632 | merge sort to understand merge sortwe take an unsorted array as the following we know that merge sort first divides the whole array iteratively into equal halves unless the atomic values are achieved we see here that an array of items is divided into two arrays of size this does not change the sequence of appearance of... |
21,633 | by definitionif it is only one element in the listit is sorted thenmerge sort combines the smaller sorted lists keeping the new list sorted too step if it is only one element in the list it is already sortedreturn step divide the list recursively into two halves until it can no more be divided step merge the smaller li... |
21,634 | quick sort quick sort is highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays large array is partitioned into two arrays one of which holds values smaller than the specified valuesay pivotbased on which the partition is made and another array holds values greater than the... |
21,635 | end while while rightpointer & [--rightpointerpivot do //do-nothing end while if leftpointer >rightpointer break else swap leftpointer,rightpointer end if end while swap leftpointer,right return leftpointer end function quick sort algorithm using pivot algorithm recursivelywe end up with smaller possible partitions eac... |
21,636 | heap sort heap sort is comparison based sorting technique based on binary heap data structure it is similar to selection sort where we first find the maximum element and place the maximum element at the end we repeat the same process for remaining element what is binary heaplet us first define complete binary tree comp... |
21,637 | ( ( ( ( ( applying heapify procedure to index ( ( ( ( ( the heapify procedure calls itself recursively to build heap in top down manner radix sort the lower bound for comparison based sorting algorithm (merge sortheap sortquick-sort etcis (nlogn) they cannot do better than nlogn counting sort is linear time sorting alg... |
21,638 | radix sort do following for each digit where varies from least significant digit to the most significant digit asort input array using counting sort (or any stable sortaccording to the 'th digit exampleoriginalunsorted list sorting by least significant digit ( placegives[*notice that we keep before because occurred bef... |
21,639 | time thereforeit runs in linear time (nlecture- binary search for sorted arraysbinary search is more efficient than linear search the process starts from the middle of the input arrayif the target equals the element in the middlereturn its index if the target is larger than the element in the middlesearch the right hal... |
21,640 | the design and analysis of efficient data structures has long been recognized as vital subject in computing and is part of the core curriculum of computer science and computer engineering undergraduate degrees data structures and algorithms in python provides an introduction to data structures and algorithmsincluding t... |
21,641 | vi book features this book is based upon the book data structures and algorithms in java by goodrich and tamassiaand the related data structures and algorithms in +by goodrichtamassiaand mount howeverthis book is not simply translation of those other books to python in adapting the material for this bookwe have signifi... |
21,642 | vii contents and organization the for this book are organized to provide pedagogical path that starts with the basics of python programming and object-oriented design we then add foundational techniques like algorithm analysis and recursion in the main portion of the bookwe present fundamental data structures and algor... |
21,643 | viii we delay treatment of object-oriented programming in python until this is useful for those new to pythonand for those who may be familiar with pythonyet not with object-oriented programming in terms of mathematical backgroundwe assume the reader is somewhat familiar with topics from high-school mathematics even so... |
21,644 | ix about the authors michael goodrich received his ph in computer science from purdue university in he is currently chancellor' professor in the department of computer science at university of californiairvine previouslyhe was professor at johns hopkins university he is fulbright scholar and fellow of the american asso... |
21,645 | acknowledgments we have depended greatly upon the contributions of many individuals as part of the development of this book we begin by acknowledging the wonderful team at wiley we are grateful to our editorbeth golubfor her enthusiastic support of this projectfrom beginning to end the efforts of elizabeth mills and ka... |
21,646 | preface python primer python overview the python interpreter preview of python program objects in python identifiersobjectsand the assignment statement creating and using objects python' built-in classes expressionsoperatorsand precedence compound expressions and operator precedence control flow conditionals loops func... |
21,647 | contents object-oriented programming goalsprinciplesand patterns object-oriented design goals object-oriented design principles design patterns software development design pseudo-code coding style and documentation testing and debugging class definitions examplecreditcard class operator overloading and python' special ... |
21,648 | xiii recursion illustrative examples the factorial function drawing an english ruler binary search file systems analyzing recursive algorithms recursion run amok maximum recursive depth in python further examples of recursion linear recursion binary recursion multiple recursion designing recursive algorithms eliminatin... |
21,649 | contents queues the queue abstract data type array-based queue implementation double-ended queues the deque abstract data type implementing deque with circular array deques in the python collections module exercises linked lists singly linked lists implementing stack with singly linked list implementing queue with sing... |
21,650 | xv preorder and postorder traversals of general trees breadth-first tree traversal inorder traversal of binary tree implementing tree traversals in python applications of tree traversals euler tours and the template method pattern case studyan expression tree exercises priority queues the priority queue abstract data t... |
21,651 | contents collision-handling schemes load factorsrehashingand efficiency python hash table implementation sorted maps sorted search tables two applications of sorted maps skip lists search and update operations in skip list probabilistic analysis of skip lists setsmultisetsand multimaps the set adt python' mutableset ab... |
21,652 | xvii sorting and selection why study sorting algorithms merge-sort divide-and-conquer array-based implementation of merge-sort the running time of merge-sort merge-sort and recurrence equations alternative implementations of merge-sort quick-sort randomized quick-sort additional optimizations for quick-sort studying so... |
21,653 | contents exercises graph algorithms graphs the graph adt data structures for graphs edge list structure adjacency list structure adjacency map structure adjacency matrix structure python implementation graph traversals depth-first search dfs implementation and extensions breadth-first search transitive closure directed... |
21,654 | xix character strings in python useful mathematical facts bibliography index |
21,655 | python primer contents python overview the python interpreter preview of python program objects in python identifiersobjectsand the assignment statement creating and using objects python' built-in classes expressionsoperatorsand precedence compound expressions and operator precedence control flow conditionals loops fun... |
21,656 | python overview building data structures and algorithms requires that we communicate detailed instructions to computer an excellent way to perform such communications is using high-level computer languagesuch as python the python programming language was originally developed by guido van rossum in the early sand has si... |
21,657 | preview of python program as simple introductioncode fragment presents python program that computes the grade-point average (gpafor student based on letter grades that are entered by user many of the techniques demonstrated in this example will be discussed in the remainder of this at this pointwe draw attention to few... |
21,658 | objects in python python is an object-oriented language and classes form the basis for all data types in this sectionwe describe key aspects of python' object modeland we introduce python' built-in classessuch as the int class for integersthe float class for floating-point valuesand the str class for character strings ... |
21,659 | for readers familiar with other programming languagesthe semantics of python identifier is most similar to reference variable in java or pointer variable in +each identifier is implicitly associated with the memory address of the object to which it refers python identifier may be assigned to special object named nonese... |
21,660 | creating and using objects instantiation the process of creating new instance of class is known as instantiation in generalthe syntax for instantiating an object is to invoke the constructor of class for exampleif there were class named widgetwe could create an instance of that class using syntax such as widget)assumin... |
21,661 | python' built-in classes table provides summary of commonly usedbuilt-in classes in pythonwe take particular note of which classes are mutable and which are immutable class is immutable if each object of that class has fixed value upon instantiation that cannot subsequently be changed for examplethe float class is immu... |
21,662 | the int class the int and float classes are the primary numeric types in python the int class is designed to represent integer values with arbitrary magnitude unlike java and ++which support different integral types with different precisions ( intshortlong)python automatically chooses the internal representation for an... |
21,663 | sequence typesthe listtupleand str classes the listtupleand str classes are sequence types in pythonrepresenting collection of values in which the order is significant the list class is the most generalrepresenting sequence of arbitrary objects (akin to an "arrayin other languagesthe tuple class is an immutable version... |
21,664 | the tuple class the tuple class provides an immutable version of sequenceand therefore its instances have an internal representation that may be more streamlined than that of list while python uses the characters to delimit listparentheses delimit tuplewith being an empty tuple there is one important subtlety to expres... |
21,665 | the set and frozenset classes python' set class represents the mathematical notion of setnamely collection of elementswithout duplicatesand without an inherent order to those elements the major advantage of using setas opposed to listis that it has highly optimized method for checking whether specific element is contai... |
21,666 | expressionsoperatorsand precedence in the previous sectionwe demonstrated how names can be used to identify existing objectsand how literals and constructors can be used to create instances of built-in classes existing values can be combined into larger syntactic expressions using variety of special symbols and keyword... |
21,667 | different objects that happen to have values that are deemed equivalent the precise notion of equivalence depends on the data type for exampletwo strings are considered equivalent if they match character for character two sets are equivalent if they have the same contentsirrespective of order in most programming situat... |
21,668 | python carefully extends the semantics of /and to cases where one or both operands are negative for the sake of notationlet us assume that variables and that and represent respectively the dividend and divisor of quotient / and python guarantees that will equal we already saw an example of this identity with positive o... |
21,669 | notation to describe subsequences of sequence slices are described as half-open intervalswith start index that is includedand stop index that is excluded for examplethe syntax data[ : denotes subsequence including the five indices an optional "stepvaluepossibly negativecan be indicated as third parameter of the slice i... |
21,670 | partial orderbut not total orderas disjoint sets are neither "less than,"equal to,or "greater thaneach other sets also support many fundamental behaviors through named methods ( addremove)we will explore their functionality more fully in dictionarieslike setsdo not maintain well-defined order on their elements furtherm... |
21,671 | compound expressions and operator precedence programming languages must have clear rules for the order in which compound expressionssuch as are evaluated the formal order of precedence for operators in python is given in table operators in category with higher precedence will be evaluated before those with lower preced... |
21,672 | control flow in this sectionwe review python' most fundamental control structuresconditional statements and loops common to all control structures is the syntax used in python for defining blocks of code the colon character is used to delimit the beginning of block of code that acts as body for control structure if the... |
21,673 | as simple examplea robot controller might have the following logicif door is closedopen dooradvancenotice that the final commandadvance)is not indented and therefore not part of the conditional body it will be executed unconditionally (although after opening closed doorwe may nest one control structure within anotherre... |
21,674 | loops python offers two distinct looping constructs while loop allows general repetition based upon the repeated testing of boolean condition for loop provides convenient iteration of values from defined series (such as characters of stringelements of listor numbers within given rangewe discuss both forms in this secti... |
21,675 | for loops python' for-loop syntax is more convenient alternative to while loop when iterating through series of elements the for-loop syntax can be used on any type of iterable structuresuch as listtuple strsetdictor file (we will discuss iterators more formally in section its general syntax appears as follows for elem... |
21,676 | index-based for loops the simplicity of standard for loop over the elements of list is wonderfulhoweverone limitation of that form is that we do not know where an element resides within the sequence in some applicationswe need knowledge of the index of an element within the sequence for examplesuppose that we want to k... |
21,677 | functions in this sectionwe explore the creation of and use of functions in python as we did in section we draw distinction between functions and methods we use the general term function to describe traditionalstateless function that is invoked without the context of particular class or an instance of that classsuch as... |
21,678 | return statement return statement is used within the body of function to indicate that the function should immediately cease executionand that an expressed value should be returned to the caller if return statement is executed without an explicit argumentthe none value is automatically returned likewisenone will be ret... |
21,679 | these assignment statements establish identifier data as an alias for grades and target as name for the string literal (see figure grades data target list str figure portrayal of parameter passing in pythonfor the function call count(gradesa identifiers data and target are formal parameters defined within the local sco... |
21,680 | default parameter values python provides means for functions to support more than one possible calling signature such function is said to be polymorphic (which is greek for "many forms"most notablyfunctions can declare one or more default values for parametersthereby allowing the caller to invoke function with varying ... |
21,681 | as an additional example of an interesting polymorphic functionwe consider python' support for range (technicallythis is constructor for the range classbut for the sake of this discussionwe can treat it as pure function three calling syntaxes are supported the one-parameter formrange( )generates sequence of integers fr... |
21,682 | by defaultmax operates based upon the natural order of elements according to the operator for that type but the maximum can be computed by comparing some other aspect of the elements this is done by providing an auxiliary function that converts natural element to some other value for the sake of comparison for examplei... |
21,683 | calling syntax abs(xall(iterableany(iterablechr(integerdivmod(xyhash(objid(objinput(promptisinstance(objclsiter(iterablelen(iterablemap(fiter iter max(iterablemax(abcmin(iterablemin(abcnext(iteratoropen(filenamemodeord(charpow(xypow(xyzprint(obj obj range(stoprange(startstoprange(startstopstepreversed(sequenceround(xro... |
21,684 | simple input and output in this sectionwe address the basics of input and output in pythondescribing standard input and output through the user consoleand python' support for reading and writing text files console input and output the print function the built-in functionprintis used to generate standard output to the c... |
21,685 | when reading numeric value from the usera programmer must use the input function to get the string of charactersand then use the int or float syntax to construct the numeric value that character string represents that isif call to response inputreports that the user entered the characters the syntax int(responsecould b... |
21,686 | when processing filethe proxy maintains current position within the file as an offset from the beginningmeasured in number of bytes when opening file with mode or the position is initially if opened in append modea the position is initially at the end of the file the syntax fp closecloses the file associated with proxy... |
21,687 | exception handling exceptions are unexpected events that occur during the execution of program an exception might result from logical error or an unanticipated situation in pythonexceptions (also known as errorsare objects that are raised (or thrownby code that encounters an unexpected circumstance the python interpret... |
21,688 | sending the wrong numbertypeor value of parameters to function is another common cause for an exception for examplea call to abshello will raise typeerror because the parameter is not numericand call to abs( will raise typeerror because one parameter is expected valueerror is typically raised when the correct number an... |
21,689 | how much error-checking to perform within function is matter of debate checking the type and value of each parameter demands additional execution time andif taken to an extremeseems counter to the nature of python consider the built-in sum functionwhich computes sum of collection of numbers an implementation with rigor... |
21,690 | catching an exception there are several philosophies regarding how to cope with possible exceptional cases when writing code for exampleif division / is to be computedthere is clear risk that zerodivisionerror will be raised when variable has value in an ideal situationthe logic of the program may dictate that has nonz... |
21,691 | exception handling is particularly useful when working with user inputor when reading from or writing to filesbecause such interactions are inherently less predictable in section we suggest the syntaxfp opensample txt )for opening file with read access that command may raise an ioerror for variety of reasonssuch as non... |
21,692 | will be unchangedthe while loop will continue if we preferred to have the while loop continue without printing the invalid response messagewe could have written the exception-clause as except (valueerroreoferror)pass the keywordpassis statement that does nothingyet it can serve syntactically as body of control structur... |
21,693 | iterators and generators in section we introduced the for-loop syntax beginning asfor element in iterableand we noted that there are many types of objects in python that qualify as being iterable basic container typessuch as listtupleand setqualify as iterable types furthermorea string can produce an iteration of its c... |
21,694 | we see lazy evaluation used in many of python' libraries for examplethe dictionary class supports methods keys)values)and items)which respectively produce "viewof all keysvaluesor (key,valuepairs within dictionary none of these methods produces an explicit list of results insteadthe views that are produced are iterable... |
21,695 | until yield statement indicates the next value at that pointthe procedure is temporarily interruptedonly to be resumed when another value is requested when the flow of control naturally reaches the end of our procedure (or zero-argument return statement) stopiteration exception is automatically raised although this par... |
21,696 | additional python conveniences in this sectionwe introduce several features of python that are particularly convenient for writing cleanconcise code each of these syntaxes provide functionality that could otherwise be accomplished using functionality that we have introduced earlier in this howeverat timesthe new syntax... |
21,697 | comprehension syntax very common programming task is to produce one series of values based upon the processing of another series oftenthis task can be accomplished quite simply in python using what is known as comprehension syntax we begin by demonstrating list comprehensionas this was the first form to be supported by... |
21,698 | packing and unpacking of sequences python provides two additional conveniences involving the treatment of tuples and other sequence types the first is rather cosmetic if series of comma-separated expressions are given in larger contextthey will be treated as single tupleeven if no enclosing parentheses are provided for... |
21,699 | simultaneous assignments the combination of automatic packing and unpacking forms technique known as simultaneous assignmentwhereby we explicitly assign series of values to series of identifiersusing syntaxxyz in effectthe right-hand side of this assignment is automatically packed into tupleand then automatically unpac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.