id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
12,700 | notice that the print_exp function as we have implemented it puts parentheses around each number while not incorrectthe parentheses are clearly not needed in the exercises at the end of this you are asked to modify the print_exp function to remove this set of parentheses binary search trees we have already seen two dif... |
12,701 | figure simple binary search tree the tree filledso the next key is going to be the left or right child of either or since is greater than and it becomes the right child of similarly is less than and so it becomes the left child of is also less than so it must be in the left subtree of howeverit is greater than so it be... |
12,702 | with these helper functionsis shown below as you can see in the code many of these helper functions help to classify node according to its own position as child(left or rightand the kind of children the node has the treenode class will also explicitly keep track of the parent as an attribute of each node you will see w... |
12,703 | another interesting aspect of the implementation of treenode is that we use python' optional parameters optional parameters make it easy for us to create treenode under several different circumstances sometimes we will want to construct new treenode that already has both parent and child with an existing parent and chi... |
12,704 | figure inserting node with key self _put(keyvalcurrent_node right_childelsecurrent_node right_child treenode(keyvalparent=current_nodewith the put method definedwe can easily overload the [operator for assignment by having the __setitem__ method call the put method this allows us to write python statements like my_zip_... |
12,705 | once the tree is constructedthe next task is to implement the retrieval of value for given key the get method is even easier than the put method because it simply searches the tree recursively until it gets to non-matching leaf node or finds matching key when matching key is foundthe value stored in the payload of the ... |
12,706 | elif key current_node keyreturn self _get(keycurrent_node left_childelsereturn self _get(keycurrent_node right_childdef __getitem__(selfkey)return self get(keyusing getwe can implement the in operation by writing __contains__ method for the binarysearchtree the __contains__ method will simply call get and return true i... |
12,707 | figure deleting node node without children the node to be deleted has no children (see figure the node to be deleted has only one child (see figure the node to be deleted has two children (see figure the first case is straightforward if the current node has no children all we need to do is delete the node and remove th... |
12,708 | figure deleting node node that has single child if current_node has_left_child()if current_node is_left_child()current_node left_child parent current_node parent current_node parent left_child current_node left_child elif current_node is_right_child()current_node left_child parent current_node parent current_node paren... |
12,709 | figure deleting node node with two children we simply put it in the tree in place of the node to be deleted the code to handle the third case is shown below notice that we make use of the helper methods find_successor and find_min to find the successor to remove the successorwe make use of the method splice_out the rea... |
12,710 | the find_min method is called to find the minimum key in subtree you should convince yourself that the minimum valued key in any binary search tree is the leftmost child of the tree therefore the find_min method simply follows the left_child references in each node of the subtree until it reaches node that does not hav... |
12,711 | python provides us with very powerful function to use when creating an iterator the function is called yield yield is similar to return in that it returns value to the caller howeveryield also takes the additional step of freezing the state of the function so that the next time the function is called it continues execu... |
12,712 | def is_leaf(self)return not (self right_child or self left_childdef has_any_children(self)return self right_child or self left_child def has_both_children(self)return self right_child and self left_child def replace_node_data(selfkeyvaluelcrc)self key key self payload value self left_child lc self right_child rc if sel... |
12,713 | def __setitem__(selfkv)self put(kvdef get(selfkey)if self rootres self _get(keyself rootif resreturn res payload elsereturn none elsereturn none def _get(selfkeycurrent_node)if not current_nodereturn none elif current_node key =keyreturn current_node elif key current_node keyreturn self _get(keycurrent_node left_childe... |
12,714 | if self is_leaf()if self is_left_child()self parent left_child none elseself parent right_child none elif self has_any_children()if self has_left_child()if self is_left_child()self parent left_child self left_child elseself parent right_child self left_child self left_child parent self parent elseif self is_left_child(... |
12,715 | elsethis node has one child if current_node has_left_child()if current_node is_left_child()current_node left_child parent current_node parent current_node parent left_child current_node left_child elif current_node is_right_child()current_node left_child parent current_node parent current_node parent right_child curren... |
12,716 | figure skewed binary search tree would give poor performance the keys are added to the tree if the keys are added in random orderthe height of the tree is going to be around log where is the number of nodes in the tree this is because if the keys are randomly distributedabout half of them will be less than the root and... |
12,717 | 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... |
12,718 | 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... |
12,719 | 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... |
12,720 | 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... |
12,721 | 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... |
12,722 | 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... |
12,723 | 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... |
12,724 | 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 ... |
12,725 | 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... |
12,726 | 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... |
12,727 | 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... |
12,728 | 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... |
12,729 | 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... |
12,730 | 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... |
12,731 | xix character strings in python useful mathematical facts bibliography index |
12,732 | 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... |
12,733 | 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... |
12,734 | 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... |
12,735 | 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 ... |
12,736 | 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... |
12,737 | 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... |
12,738 | 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... |
12,739 | 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... |
12,740 | 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... |
12,741 | 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... |
12,742 | 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... |
12,743 | 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... |
12,744 | 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... |
12,745 | 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... |
12,746 | 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... |
12,747 | 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... |
12,748 | 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... |
12,749 | 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... |
12,750 | 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... |
12,751 | 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... |
12,752 | 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... |
12,753 | 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... |
12,754 | 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... |
12,755 | 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... |
12,756 | 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... |
12,757 | 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 ... |
12,758 | 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... |
12,759 | 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... |
12,760 | 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... |
12,761 | 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... |
12,762 | 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... |
12,763 | 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... |
12,764 | 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... |
12,765 | 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... |
12,766 | 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... |
12,767 | 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... |
12,768 | 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... |
12,769 | 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... |
12,770 | 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... |
12,771 | 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... |
12,772 | 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... |
12,773 | 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... |
12,774 | 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... |
12,775 | 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... |
12,776 | 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... |
12,777 | scopes and namespaces when computing sum with the syntax in pythonthe names and must have been previously associated with objects that serve as valuesa nameerror will be raised if no such definitions are found the process of determining the value associated with an identifier is known as name resolution whenever an ide... |
12,778 | when an identifier is indicated in commandpython searches series of namespaces in the process of name resolution firstthe most locally enclosing scope is searched for given name if not found therethe next outer scope is searchedand so on we will continue our examination of namespacesin section when discussing python' t... |
12,779 | modules and the import statement we have already introduced many functions ( maxand classes ( listthat are defined within python' built-in namespace depending on the version of pythonthere are approximately - definitions that were deemed significant enough to be included in that built-in namespace beyond the built-in d... |
12,780 | it is worth noting that top-level commands with the module source code are executed when the module is first importedalmost as if the module were its own script there is special construct for embedding commands within the module that will be executed if the module is directly invoked as scriptbut not when the module is... |
12,781 | next number in sequence based upon one or more past numbers that it has generated indeeda simple yet popular pseudo-random number generator chooses its next number based solely on the most recently chosen number and some additional parameters using the following formula next ( *current bnwhere aband are appropriately c... |
12,782 | exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - write short python functionis multiple(nm)that takes two integer values and returns true if is multiple of mthat isn mi for some integer iand false otherwise - write short python functionis even( )that takes an integer ... |
12,783 | creativity - write pseudo-code description of function that reverses list of integersso that the numbers are listed in the opposite order than they were beforeand compare this method to an equivalent python function for doing the same thing - write short python function that takes sequence of integer values and determi... |
12,784 | - write short python program that takes two arrays and of length storing int valuesand returns the dot product of and that isit returns an array of length such that [ia[ib[ ]for - give an example of python code fragment that attempts to write an element to list based on an index that may be out of bounds if that index ... |
12,785 | projects - write python program that outputs all possible strings formed by using the characters and exactly once - write python program that can take positive integer greater than as input and write out the number of times one must repeatedly divide this number by before getting value less than - write python program ... |
12,786 | notes the official python web site (modules the python interpreter is itself useful referenceas the interactive command help(fooprovides documentation for any functionclassor module that foo identifies books providing an introduction to programming in python include titles authored by campbell et al [ ]cedar [ ]dawson ... |
12,787 | object-oriented programming contents 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 ... |
12,788 | goalsprinciplesand patterns as the name impliesthe main "actorsin the object-oriented paradigm are called objects each object is an instance of class each class presents to the outside world concise and consistent view of the objects that are instances of this classwithout going into too much unnecessary detail or givi... |
12,789 | adaptability modern software applicationssuch as web browsers and internet search enginestypically involve large programs that are used for many years softwarethereforeneeds to be able to evolve over time in response to changing conditions in its environment thusanother important goal of quality software is that it ach... |
12,790 | modularity modern software systems typically consist of several different components that must interact correctly in order for the entire system to work properly keeping these interactions straight requires that these different components be well organized modularity refers to an organizing principle in which different... |
12,791 | as programming languagepython provides great deal of latitude in regard to the specification of an interface python has tradition of treating abstractions implicitly using mechanism known as duck typing as an interpreted and dynamically typed languagethere is no "compile timechecking of data types in pythonand no forma... |
12,792 | design patterns object-oriented design facilitates reusablerobustand adaptable software designing good code takes more than simply understanding object-oriented methodologieshowever it requires the effective use of object-oriented design techniques computing researchers and practitioners have developed variety of organ... |
12,793 | software development traditional software development involves several phases three major steps are design implementation testing and debugging in this sectionwe briefly discuss the role of these phasesand we introduce several good practices for programming in pythonincluding coding stylenaming conventionsformal docume... |
12,794 | common tool for developing an initial high-level design for project is the use of crc cards class-responsibility-collaborator (crccards are simple index cards that subdivide the work required of program the main idea behind this tool is to have each card represent componentwhich will ultimately become class in the prog... |
12,795 | pseudo-code as an intermediate step before the implementation of designprogrammers are often asked to describe algorithms in way that is intended for human eyes only such descriptions are called pseudo-code pseudo-code is not computer programbut is more structured than usual prose it is mixture of natural language and ... |
12,796 | use meaningful names for identifiers try to choose names that can be read aloudand choose names that reflect the actionresponsibilityor data each identifier is naming classes (other than python' built-in classesshould have name that serves as singular nounand should be capitalized ( date rather than date or dateswhen m... |
12,797 | documentation python provides integrated support for embedding formal documentation directly in source code using mechanism known as docstring formallyany string literal that appears as the first statement within the body of moduleclassor function (including member function of classwill be considered to be docstring by... |
12,798 | testing and debugging testing is the process of experimentally checking the correctness of programwhile debugging is the process of tracking the execution of program and discovering the errors in it testing and debugging are often the most time-consuming activity in the development of program testing careful testing pl... |
12,799 | bottom-up testing proceeds from lower-level components to higher-level components for examplebottom-level functionswhich do not invoke other functionsare tested firstfollowed by functions that call only bottom-level functionsand so on similarly class that does not depend upon any other classes can be tested before anot... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.