id
int64
0
25.6k
text
stringlengths
0
4.59k
12,600
implement the remaining operations defined in the unorderedlist adt (appendindexpopinsert implement slice method for the unorderedlist class it should take two parametersstart and stopand return copy of the list starting at the start position and going up to but not including the stop position implement the remaining o...
12,601
basic data structures
12,602
four recursion objectives the goals for this are as followsto understand that complex problems that may otherwise be difficult to solve may have simple recursive solution to learn how to formulate programs recursively to understand and apply the three laws of recursion to understand recursion as form of iteration to im...
12,603
for in num_listthe_sum the_sum return the_sum print(list_sum([ , , , , ])pretend for minute that you do not have while loops or for loops how would you compute the sum of list of numbersif you were mathematician you might start by recalling that addition is function that is defined for two parametersa pair of numbers t...
12,604
figure series of recursive calls adding list of numbers itselfthis is the reason that we call the list_sum algorithm recursive recursive function is function that calls itself figure shows the series of recursive calls that are needed to sum the list [ you should think of this series of calls as series of simplificatio...
12,605
figure series of recursive returns from adding list of numbers usually the data that represents our problem gets smaller in some way in the list_sum algorithm our primary data structure is listso we must focus our state-changing efforts on the list since the base case is list of length natural progression toward the ba...
12,606
suppose you are going to write recursive function to calculate the factorial of number fact(nreturns where the factorial of zero is defined to be what would be the most appropriate base case = = > < converting an integer to string in any base suppose you want to convert an integer to string in some base between binary ...
12,607
figure converting an integer to string in base the code below shows the python code that implements the algorithm outlined above for any base between and def to_str(nbase)convert_string " abcdefif basereturn convert_string[nelsereturn to_str( basebaseconvert_string[ base print(to_str( )notice that in line we check for ...
12,608
figure converting an integer to string in base write function that takes string as parameter and returns true if the string is palindromefalse otherwise remember that string is palindrome if it is spelled the same both forward and backward for exampleradar is palindrome for bonus points palindromes can also be phrasesb...
12,609
r_stack stack(def to_str(nbase)convert_string " abcdefwhile if baser_stack push(convert_string[ ]elser_stack push(convert_string[ base] /base res "while not r_stack is_empty()res res str(r_stack pop()return res print(to_str( )each time we make call to tostrwe push character on the stack returning to the previous exampl...
12,610
figure call stack generated from tostr( , if you keep this idea of the stack in your headyou will find it much easier to write proper recursive function visualising recursion in the previous section we looked at some problems that were easy to solve using recursionhoweverit can still be difficult to find mental model o...
12,611
import turtle my_turtle turtle turtle(my_win turtle screen(def draw_spiral(my_turtleline_len)if linelen my_turtle forward(line_lenmy_turtle right( draw_spiral(my_turtleline_len draw_spiral(my_turtle my_win exitonclick(that is really about all the turtle graphics you need to know in order to make some pretty impressive ...
12,612
left( tree(branch_len ,tt right( backward(branch_lenthe complete program for this tree example is shown below before you run the code think about how you expect to see the tree take shape look at the recursive calls and think about how this tree will unfold will it be drawn symmetrically with the right and left halves ...
12,613
figure the beginning of fractal tree recursion
12,614
figure the first half of the tree visualising recursion
12,615
self check modify the recursive tree program using one or all of the following ideasmodify the thickness of the branches so that as the branchlen gets smallerthe line gets thinner modify the color of the branches so that as the branchlen gets very short it is colored like leaf modify the angle used in turning the turtl...
12,616
figure the sierpinski triangle def sierpinski(pointsdegreemy_turtle)color_map ['blue''red''green''white''yellow''violet''orange'draw_triangle(pointscolor_map[degree]my_turtleif degree sierpinski([points[ ]get_mid(points[ ]points[ ])get_mid(points[ ]points[ ])]degree- my_turtlesierpinski([points[ ]get_mid(points[ ]point...
12,617
figure building sierpinski triangle main(the first thing sierpinski does is draw the outer triangle nextthere are three recursive callsone for each of the new corner triangles we get when we connect the midpoints once again we make use of the standard turtle module that comes with python you can learn all the details o...
12,618
figure an example arrangement of disks for the tower of hanoi complex recursive problems in the previous sections we looked at some problems that are relatively easy to solve and some graphically interesting problems that can help us gain mental model of what is happening in recursive algorithm in this section we will ...
12,619
and then move the tower of four from peg two to peg three but what if you do not know how to move tower of height foursuppose that you knew how to move tower of height three to peg threethen it would be easy to move the fourth disk to peg two and move the three from peg three on top of it but what if you do not know ho...
12,620
def move_tower(heightfrom_poleto_polewith_pole)if height > move_tower(height from_polewith_poleto_polemove_disk(from_poleto_polemove_tower(height with_poleto_polefrom_poledef move_disk(fp,tp)print("moving disk from",fp,"to",tp move_tower( " "" "" "now that you have seen the code for both movetower and movediskyou may b...
12,621
figure the finished maze search program recursion
12,622
also be to the north but if the north is blocked by wall we must look at the next step of the procedure and try going to the south unfortunately that step to the south brings us right back to our original starting place if we apply the recursive procedure from there we will just go back one step to the north and be in ...
12,623
we have found square that has already been explored if maze[start_row][start_column=triedreturn false successan outside edge not occupied by an obstacle if maze is_exit(start_rowstart_column)maze update_position(start_rowstart_columnpart_of_pathreturn true maze update_position(start_rowstart_columntried otherwiseuse lo...
12,624
++++++++++++ +++++++++++++++++++++the internal representation of the maze is list of lists each row of the maze_list instance variable is also list this secondary list contains one character per square using the characters described above for the data file shown above the internal representation looks like the followin...
12,625
columns_in_maze len(row_listself rows_in_maze rows_in_maze self columns_in_maze columns_in_maze self x_translate columns_in_maze self y_translate rows_in_maze self turtle(shape 'turtle'setup(width height setworldcoordinates((columns_in_maze (rows_in_maze (columns_in_maze (rows_in_maze def draw_maze(self)for in range(se...
12,626
color 'greenelif val =obstaclecolor 'redelif val =triedcolor 'blackelif val =dead_endcolor 'redelsecolor none if colorself drop_bread_crumb(colordef is_exit(selfrowcol)return (row = or row =self rows_in_maze or col = or col =self columns_in_maze def __getitem__(selfidx)return self maze_list[idxthe complete program is s...
12,627
class mazedef __init__(selfmaze_file_name)rows_in_maze columns_in_maze self maze_list [maze_file open(maze_file_name,' 'rows_in_maze for line in maze_filerow_list [col for ch in line[- ]row_list append(chif ch =' 'self start_row rows_in_maze self start_col col col col rows_in_maze rows_in_maze self maze_list append(row...
12,628
self forward( self right( self end_fill(def move_turtle(selfxy)self up(self setheading(self towards( self x_translatey self y_translate)self goto( self x_translatey self y_translatedef drop_bread_crumb(selfcolor)self dot( colordef update_position(selfrowcolval=none)if valself maze_list[row][colval self move_turtle(colr...
12,629
if maze[start_row][start_column=tried or maze[start_row][start_column=dead_endreturn false we have found an outside edge not occupied by an obstacle if maze is_exit(start_row,start_column)maze update_position(start_rowstart_columnpart_of_pathreturn true maze update_position(start_rowstart_columntriedotherwiseuse logica...
12,630
recursion is not always the answer sometimes recursive solution may be more computationally expensive than an alternative algorithm content key terms base case recursive call decrypt stack frame recursion discussion questions draw call stack for the tower of hanoi problem assume that you start with stack of three disks...
12,631
write program to solve the following problemyou have two jugsa -gallon jug and -gallon jug neither of the jugs have markings on them there is pump that can be used to fill the jugs with water how can you get exactly two gallons of water in the -gallon juggeneralize the problem above so that the parameters to your solut...
12,632
five sorting and searching objectives to be able to explain and implement sequential search and binary search to be able to explain and implement selection sortbubble sortmerge sortquick sortinsertion sortand shell sort to understand the idea of hashing as search technique to introduce the map abstract data type to imp...
12,633
figure the sequential search of list of integers the sequential search when data items are stored in collection such as listwe say that they have linear or sequential relationship each data item is stored in position relative to the others in python liststhese relative positions are the index values of the individual i...
12,634
case best case worst case average case item is present item is not present table comparisons used in sequential search of an unordered list figure sequential search of an ordered list of integers list in other wordsthe probability that the item we are looking for is in any particular position is exactly the same for ea...
12,635
case item is present item is not present best case worst case average case table comparisons used in sequential search of an ordered list if a_list[positemstop true elsepos pos+ return found test_list [ ,print(ordered_sequential_search(test_list )print(ordered_sequential_search(test_list )table summarizes these results...
12,636
figure binary search of an ordered list of integers list in sequencea binary search will start by examining the middle item if that item is the one we are searching forwe are done if it is not the correct itemwe can use the ordered nature of the list to eliminate half of the remaining items if the item we are searching...
12,637
comparisons ** approximate number of items left ** table tabular analysis for binary search def binary_search(a_listitem)if len(a_list= return false elsemidpoint len(a_list/ if a_list[midpoint=itemreturn true elseif item a_list[midpoint]return binary_search(a_list[:midpoint]itemelsereturn binary_search(a_list[midpoint ...
12,638
that for small values of nthe additional cost of sorting is probably not worth it in factwe should always consider whether it is cost effective to take on the extra work of sorting to gain searching benefits if we can sort once and then search many timesthe cost of the sort is not so significant howeverfor large listss...
12,639
figure hash table with empty slots item hash value table simple hash function using remainders the mapping between an item and the slot where that item belongs in the hash table is called the hash function the hash function will take any item in the collection and return an integer in the range of slot namesbetween and...
12,640
we would have problem according to the hash functiontwo or more items would need to be in the same slot this is referred to as collision (it may also be called "clash"clearlycollisions create problem for the hashing technique we will discuss them in detail later hash functions given collection of itemsa hash function t...
12,641
item remainder mid-square table comparisons of remainder and mid-square methods figure hashing string using ordinal values we can then take these three ordinal valuesadd them upand use the remainder method to get hash value (see figure the code below shows function called hash that takes string and table size and retur...
12,642
figure hashing string using ordinal values with weighting figure collision resolution with linear probing occur howeversince this is often not possiblecollision resolution becomes very important part of hashing one method for resolving collisions looks into the hash table and tries to find another open slot to hold the...
12,643
figure cluster of items for slot figure collision resolution using "plus disadvantage to linear probing is the tendency for clusteringitems become clustered in the table this means that if many collisions occur at the same hash valuea number of surrounding slots will be filled by the linear probing resolution this will...
12,644
figure collision resolution with quadratic probing figure collision resolution with quadratic probing this means that if the first hash value is hthe successive values are + + + + and so on in other wordsquadratic probing uses skip consisting of successive perfect squares figure shows our example values after they are ...
12,645
suppose you are given the following set of keys to insert into hash table that holds exactly values which of the following best demonstrates the contents of the has table after all the keys have been inserted using linear probing ____ __ __ ____ ____ implementing the map abstract data type one of the most useful python...
12,646
class hashtabledef __init__(self)self size self slots [noneself size self data [noneself size hash_function implements the simple remainder method the collision resolution technique is linear probing with "plus rehash function the put function (see listing assumes that there will eventually be an empty slot unless the ...
12,647
we leave the remaining methods as exercises def get(selfkey)start_slot self hash_function(keylen(self slots)data none stop false found false position start_slot while self slots[position!none and not found and not stopif self slots[position=keyfound true data self data[positionelseposition=self rehash(positionlen(self ...
12,648
[ 'chickenh[ 'tigerh[ ]='duckh[ 'duckh data ['bird''goat''pig''duck''dog''lion''tiger'nonenone'cow''cat'>print( [ ]none analysis of hashing we stated earlier that in the best case hashing would provide ( )constant time search technique howeverdue to collisionsthe number of comparisons is typically not so simple even th...
12,649
on the other handfor larger collectionswe want to take advantage of as many improvements as possible in this section we will discuss several sorting techniques and compare them with respect to their running time before getting into specific algorithmswe should think about the operations that can be used to analyze sort...
12,650
figure bubble sortthe first pass a_list[jtemp will exchange the ith and th items in the list without the temporary storageone of the values would be overwritten in pythonit is possible to perform simultaneous assignment the statement ab ba will result in two assignment statements being done at the same time (see figure...
12,651
figure exchanging two values in python pass - comparisons - - - table comparisons for each pass of bubble sort it has the capability to do something most sorting algorithms cannot in particularif during pass there are no exchangesthen we know that the list must be sorted bubble sort can be modified to stop early if it ...
12,652
pass_num pass_num a_list=[ short_bubble_sort(a_listprint(a_listself check suppose you have the following list of numbers to sort[ which list represents the partially sorted list after three complete passes of bubble sort [ [ [ [ selection sort the selection sort improves on the bubble sort by making only one exchange f...
12,653
figure selection sort sorting and searching
12,654
selection sort typically executes faster in benchmark studies in factfor our listthe bubble sort makes exchangeswhile the selection sort makes only self check suppose you have the following list of numbers to sort[ which list represents the partially sorted list after three complete passes of selection sort [ [ [ [ the...
12,655
figure insertion sort def insertion_sort(a_list)for index in range( len(a_list))current_value a_list[indexposition index while position and a_list[position current_valuea_list[positiona_list[position position position a_list[positioncurrent_value a_list [ insertion_sort(a_listprint(a_listself check suppose you have the...
12,656
figure insertion sortfifth pass of the sort [ [ [ [ shell sort the shell sortsometimes called the "diminishing increment sort,improves on the insertion sort by breaking the original list into number of smaller sublistseach of which is sorted using an insertion sort the unique way that these sublists are chosen is the k...
12,657
figure shell sort with increments of three figure shell sort after sorting each sublist is sorted with the basic insertion sort figure shows the first sublists for our example using this increment the following invocation of the shell_sort function shows the partially sorted lists after each incrementwith the final sor...
12,658
figure shell sorta final insertion sort with increment of figure initial sublists for shell sort while position >gap and a_list[position gapcurrent_valuea_list[positiona_list[position gapposition position gap a_list[positioncurrent_value a_list [ shell_sort(a_listprint(a_listat first glance you may think that shell sor...
12,659
although general analysis of the shell sort is well beyond the scope of this textwe can say that it tends to fall somewhere between (nand ( )based on the behaviour described above by changing the incrementfor example using ( and so on) shell sort can perform at ( self check given the following list of numbers[ which an...
12,660
figure splitting the list in merge sort figure lists as they are merged together sorting
12,661
while len(left_halfand len(right_half)if left_half[iright_half[ ]a_list[kleft_half[ii elsea_list[kright_half[jj while len(left_half)a_list[kleft_half[ii while len(right_half)a_list[kright_half[jj print("merging "a_list a_list [ merge_sort(a_listprint(a_listonce the merge_sort function is invoked on the left half and th...
12,662
halves as they are extracted with the slicing operations this additional space can be critical factor if the list is large and can make this sort problematic when working on large data sets self check given the following list of numbers[ which answer illustrates the list to be sorted after recursive calls to mergesort ...
12,663
partitioning begins by locating two position markers let' call them left_mark and right_mark at the beginning and end of the remaining items in the list (positions and in figure the goal of the partition process is to move items that are on the wrong side with respect to the pivot value while also converging on the spl...
12,664
figure finding the split point for sorting
12,665
figure completing the partition process to find the split point for right_mark right_mark if right_mark left_markdone true elsetemp a_list[left_marka_list[left_marka_list[right_marka_list[right_marktemp temp a_list[firsta_list[firsta_list[right_marka_list[right_marktemp return right_mark a_list [ quick_sort(a_listprint...
12,666
of the listthe median of three will choose better "middlevalue this will be particularly useful when the original list is somewhat sorted to begin with we leave the implementation of this pivot value selection as an exercise self check given the following list of numbers [ which answer shows the contents of the list af...
12,667
key terms binary search clustering folding method hash table linear probing median of three mid-square method perfect hash function quick sort sequential search slot bubble sort collision gap hashing load factor merge open addressing pivot value rehashing shell sort split point chaining collision resolution hash functi...
12,668
quick sort (you decide on the pivot value consider the following list of integers[ show how this list is sorted by the following algorithmsbubble sort selection sort insertion sort shell sort (you decide on the incrementsmerge sort quick sort (you decide on the pivot value consider the following list of integers[ show ...
12,669
(recursive and iterativegenerate randomordered list of integers and do benchmark analysis for each one what are your resultscan you explain them implement the binary search using recursion without the slice operator recall that you will need to pass the list along with the starting and ending index values for the subli...
12,670
six trees and tree algorithms objectives to understand what tree data structure is and how it is used to see how trees can be used to implement map data structure to implement trees using list to implement trees using classes and references to implement trees as recursive data structure to implement priority queue usin...
12,671
figure taxonomy of some common animals shown as tree trees and tree algorithms
12,672
figure small part of the unix file system hierarchy third property is that each leaf node is unique we can specify path from the root of the tree to leaf that uniquely identifies each species in the animal kingdomfor exampleanimalia chordate mammal carnivora felidae felis domestica another example of tree structure tha...
12,673
figure tree corresponding to the markup elements of web page inside the pair if you checkyou will see that this nesting property is true at all levels of the tree vocabulary and definitions vocabulary node node is fundamental part of tree it can have namewhich we call the "key node may also have additional information ...
12,674
figure tree consisting of set of nodes and edges sibling nodes in the tree that are children of the same parent are said to be siblings the nodes etcand usrare siblings in the filesystem tree subtree subtree is set of nodes and edges comprised of parent and all the descendants of that parent leaf node leaf node is node...
12,675
figure recursive definition of tree by an edge figure illustrates this recursive definition of tree using the recursive definition of treewe know that the tree in figure has at least four nodessince each of the triangles representing subtree must have root it may have many more nodes than thatbut we do not know unless ...
12,676
figure small tree list of lists representation in tree represented by list of listswe will begin with python' list data structure and write the functions defined above although writing the interface as set of operations on list is bit different from the other abstract data types we have implementedit is interesting to ...
12,677
let us formalize this definition of the tree data structure by providing some functions that make it easy for us to use lists as trees note that we are not going to define binary tree class the functions we will write will just help us manipulate standard list as though we are working with tree def binary_tree( )return...
12,678
def get_right_child(root)return root[ the following code exercises the tree functions we have just written you should try it out for yourself one of the exercises asks you to draw the tree structure resulting from this set of calls def binary_tree( )return [ [][]def insert_left(rootnew_branch) root pop( if len( root in...
12,679
print(get_right_child(get_right_child( ))self check given the following statementsx binary_tree(' 'insert_left( ,' 'insert_right( ,' 'insert_right(get_right_child( )' 'insert_left(get_right_child(get_right_child( ))' 'which of the answers is the correct representation of the tree [' '[' '[][]][' '[][' '[][]]] [' '[' '[...
12,680
figure simple tree using nodes and references approach modify self left_child in the root to reference the new tree class binarytreedef __init__(selfroot)self key root self left_child none self right_child none notice that the constructor function expects to get some kind of object to store in the root just like you ca...
12,681
def insert_right(self,new_node)if self right_child =noneself right_child binarytree(new_nodeelset binarytree(new_nodet right_child self right_child self right_child to round out the definition for simple binary tree data structurewe will write accessor methods for the left and right childrenas well as the root values d...
12,682
binarytree(new_nodet right_child self right_child self right_child def get_right_child(self)return self right_child def get_left_child(self)return self left_child def set_root_val(selfobj)self key obj def get_root_val(self)return self key binarytree(' 'print( get_root_val()print( get_left_child() insert_left(' 'print( ...
12,683
priority queues with binary heaps in earlier sections you learned about the first-in first-out data structure called queue one important variation of queue is called priority queue priority queue acts like queue in that you dequeue an item by removing it from the front howeverin priority queue the logical order of item...
12,684
figure complete binary tree print(bh del_min() print(bh del_min() print(bh del_min() print(bh del_min() binary heap implementation the structure property in order to make our heap work efficientlywe will take advantage of the logarithmic nature of the binary tree to represent our heap in order to guarantee logarithmic ...
12,685
figure complete binary tree along with its list representation traverse complete binary tree using only few simple mathematical operations we will see that this also leads to an efficient implementation of our binary heap the heap order property the method that we will use to store items in heap relies on maintaining t...
12,686
appending is that it guarantees that we will maintain the complete tree property the bad news about appending is that we will very likely violate the heap structure property howeverit is possible to write method that will allow us to regain the heap structure property by comparing the newly added item with its parent i...
12,687
notice that we can compute the parent of any node by using simple integer division the parent of the current node can be computed by dividing the index of the current node by def perc_up(selfi)while / if self heap_list[iself heap_list[ / ]tmp self heap_list[ / self heap_list[ / self heap_list[iself heap_list[itmp / we ...
12,688
figure percolating the root node down the tree priority queues with binary heaps
12,689
elseif self heap_list[ self heap_list[ ]return elsereturn the code for the del_min operation is below note that once again the hard work is handled by helper functionin this case perc_down def del_min(self)ret_val self heap_list[ self heap_list[ self heap_list[self current_sizeself current_size self current_size self h...
12,690
figure building heap from the list [ priority queues with binary heaps
12,691
figure parse tree for simple sentence the assertion that we can build the heap in (nmay seem bit mysterious at firstand proof is beyond the scope of this book howeverthe key to understanding that you can build the heap in (nis to remember that the log factor is derived from the height of the tree for most of the work i...
12,692
figure parse tree for (( ( )replace an entire subtree with one node once we have evaluated the expressions in the children applying this replacement procedure gives us the simplified tree shown in figure simplified parse tree for (( ( )in the rest of this section we are going to examine parse trees in more detail in pa...
12,693
before writing the python codelet' look at an example of the rules outlined above in action we will use the expression ( ( )we will parse this expression into the following list of character tokens ['('' ''+''('' ''*'' ,')'')'initially we will start out with parse tree that consists of an empty root node figure illustr...
12,694
( ( ( ( ( ( ( (hfigure tracing parse tree construction binary tree applications
12,695
if ='('current_tree insert_left(''p_stack push(current_treecurrent_tree current_tree get_left_child(elif not in ['+''-''*''/'')']current_tree set_root_val(int( )parent p_stack pop(current_tree parent elif in ['+''-''*''/']current_tree set_root_val(icurrent_tree insert_right(''p_stack push(current_treecurrent_tree curre...
12,696
the current node is not leaf nodelook up the operator in the current node and apply it to the results from recursively evaluating the left and right children to implement the arithmeticwe use dictionary with the keys '+''-''*'and '/the values stored in the dictionary are functions from python' operator module the opera...
12,697
figure representing book as tree tree traversals now that we have examined the basic functionality of our tree data structureit is time to look at some additional usage patterns for trees these usage patterns can be divided into the three ways that we access the nodes of the tree there are three commonly used patterns ...
12,698
subtree of which is section as before we visit the left subtreewhich brings us to section then we visit the node for section with section finishedwe return to then we return to the book node and follow the same procedure for the code for writing tree traversals is surprisingly elegantlargely because the traversals are ...
12,699
we have already seen common use for the postorder traversalnamely evaluating parse tree look back at our evaluate function above what we are doing is evaluating the left subtreeevaluating the right subtreeand combining them in the root through the function call to an operator assume that our binary tree is going to sto...