id
int64
0
25.6k
text
stringlengths
0
4.59k
14,500
sequences computers are really good at dealing with large amounts of information they can repeat task over and over again without getting bored when they repeat task they are generally doing the same thing to similar data or objects it is natural to want to organize those objects into some kind of structure so that our...
14,501
sequences what is the complexity of many of the common operations on sequences and how is that complexity affected by the underlying organization of the data you will also be presented with few interesting programming problems that will help you learn to select and use appropriate data structures to solve some interest...
14,502
the pylist datatype in the first couple of we began developing our pylist data structure to support the ( complexity of the append operationthe pylist contains empty locations that can be filled when append is called as first described in sect we'll keep track of the number of locations being used and the actual size o...
14,503
sequences fig sample pylist object the programmer pass in list or sequence to put in the list initially for instancethe object in fig could have been created by writing the following samplelist pylist([" "" "" "]each element of the sequence is added as separate list item the complexity of creating pylist object is ( if...
14,504
pylist concatenate def __add__(self,other)result pylist(size=self numitems+other numitems for in range(self numitems)result append(self items[ ] for in range(other numitems)result append(other items[ ] return result to concatenate two lists we must build new list that contains the contents of both this is an accessor m...
14,505
sequences as we learned in chap to make the append operation run in ( time we can' just add one more location each time we need more space it turns out that adding more space each time is enough to guarantee ( complexity the choice of is not significant if we added even more space each time we would get ( complexity at...
14,506
pylist delete def __delitem__(self,index)for in range(indexself numitems- )self items[iself items[ + self numitems - same as writing self numitems self numitems when deleting an item at specific index in the listwe must move everything after the item down to preserve our invariant that there are no holes in the interna...
14,507
sequences pylist length def __len__(self)return self numitems if the number of items were not kept track of within the pylist objectthen counting the number of items in the list would be (noperation insteadif we keep track of the number of items in the list as items are appended or deleted from the listthen we need onl...
14,508
pylist string representation def __repr__(self) "pylist([for in range(self numitems) repr(self items[ ]if self numitems " "])return the other method for converting an object to string has different purpose python includes function called eval that will take string containing an expression and evaluate the expression in...
14,509
sequences which is bettershallow cloning or deep cloningdepends on the application being written one is not necessarily better than the other there is an additional performance and memory hit for making deep clones but they are safer the type of application being developed will probably help determine which type of clo...
14,510
python ( : feb : : [gcc (apple inc build )type "help""copyright""creditsor "licensefor more information [evaluate untitled- pylst [ , , lst list("abc"lst [' '' '' 'lst lst traceback (most recent call last)file ""line in builtins typeerrorunorderable typesint(str(lst [ , , lst lst true lst [ , , lst lst true lst [ , , l...
14,511
sequences for in range( )pair point(screen, ,jlst append(pair lst sort( for in lstprint( when the code in sect is called it prints the points in order of their distance from the -axis as follows ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , ( , butjust how does this sort method work and what is it...
14,512
selection sort' select function def select(seqstart)minindex start for in range(start+ len(seq))if seq[minindexseq[ ]minindex return minindex the start argument tells the select function where to start looking for the smallest item it searches from start to the end of the sequence for the smallest item the selection so...
14,513
sequences fig selection sort snapshot consider sorting the list [ as depicted in fig after each call of the select function from the selsort function the next element of the list is placed in its final location sorting the list leads to the intermediate steps as shown each time the select function is called the new sma...
14,514
fig selection sort of list merge sort divide and conqueras the ancient romans might have saidis an effective battle strategy it turns out this concept is very important when writing algorithms the merge sort algorithm is one instance of divide and conquer algorithm divide and conquer algorithms are usually written recu...
14,515
sequences the merge sort code def merge(seqstartmidstop)lst [ start mid merge the two lists while each has more elements while mid and stopif seq[iseq[ ]lst append(seq[ ] += elselst append(seq[ ] += copy in the rest of the start to mid sequence while midlst append(seq[ ] += many merge sort implementations copy the rest...
14,516
of the two sorted sublists are copiedin (ntimeto new list then the sorted list is copied back into the original sequenceagain in (ntime in the merge functionthe first while loop takes care of merging the two sublists until one or the other sublist is empty the second and third while loops take care of finishing up whic...
14,517
sequences fig merge sort snapshot fig merge sort merges algorithm is not ( to see whyconsider sorting the list [ after repeatedly splitting the lists we get down to lists of size one as depicted in the first list of fig the individual items are merged two at time to form sorted lists of twoshown in the second list of i...
14,518
in the second version of the listtwo merges are done for the lists of length two howevereach merge is done on one half the list the purple half is one mergethe green half includes the items that are in the second merge togetherthese two merges include all items again soat the second deepest level again at most items ar...
14,519
sequences of the pivot is to have the quicksort algorithm start by randomizing the sequence the quicksort algorithm is given in sect the quicksort code import random def partition(seqstartstop)pivotindex comes from the start location in the list pivotindex start pivot seq[pivotindexi start+ stop- while < #while < and s...
14,520
both ends and works it way to the middle essentially every time value bigger than the pivot is found on the left side and value smaller than the pivot is found on the right sidethe two values are swapped once we reach the middle from both sidesthe pivot is swapped into place once the sequence is partitionedthe quicksor...
14,521
sequences fig quicksorting list it with the last item that is less than the pivot then partitioning is performed on the resulting two sublists the randomization done in the first step of quicksort helps to pick more random pivot value this has real consequences in the quicksort algorithmespecially when the sequence pas...
14,522
fig -dimensional matrix the rowsthen the matrix is said to be in row major form if the main list contains references to the columns of the matrixthen it is in column major form most of the timematrices are constructed in row major form in fig matrix is drawn with row major orientationbut the matrix could represent eith...
14,523
sequences rowlst append(board[ ][ ] self items append(rowlst the getitem method is used to index into the board it should return row of the board that row itself is indexable (it is just listso accessing row and column in the board can be written board[row][columnbecause of this method def __getitem__(self,index)return...
14,524
many gamesboth animated and otherwiseare easy to implement using tkinter and turtle graphics animated characters or tokens in game can be implemented as turtle that moves around on the screen as necessary for the tic tac toe game the ' and ' can be implemented as rawturtles rawturtle is just like turtle object except t...
14,525
sequences the minimax algorithm the dummyxand classes all have an eval method that returns either for computer movea - for human moveor for no move yet the values for these moves are used in an algorithm called minimax the minimax algorithm is recursive algorithm that is used in two person game playing where one player...
14,526
that board howeverit does not tell you which move is the best to make to deal with this we can have the code that executes the computer' turn do little of the work for the computer turn code to find the best move it makes move in copy of the boardcalls minimax with the human as the next player to make moveand then reco...
14,527
sequences the node class class nodedef __init__(self,item,next=none)self item item self next next def getitem(self)return self item def getnext(self)return self next def setitem(selfitem)self item item def setnext(self,next)self next next in the node class there are two pieces of informationthe item is reference to val...
14,528
operation complexity usage method list creation (len( ) linkedlist(ycalls __init__(yindexed get (na [ix __getitem__(iindexed set (nx[ia __setitem__( ,aconcatenate (nz= + __add__(yappend ( append(ax append(ainsert (nx insert( ,ex insert( , )delete (ndel [ix __delitem__(iequality (nx = __eq__(yiterate (nfor in xx __iter_...
14,529
sequences and the last item in the linked list they both point to dummy node to begin with this dummy node will always be in the first position in the list and will never contain an item its purpose is to eliminate special cases in the code below self first linkedlist __node(none,noneself last self first self numitems ...
14,530
linkedlist concatenate def __add__(self,other)if type(self!type(other)raise typeerror("concatenate undefined for str(type(self)str(type(other)) result linkedlist( cursor self first getnext( while cursor !noneresult append(cursor getitem()cursor cursor getnext( cursor other first getnext( while cursor !noneresult append...
14,531
sequences the code for the append method is quite simple since the self last reference points at the node immediately preceding the place where we want to put the new nodewe just create new node and make the last one point at it then we make the new node the new self last node and increment the number of items by linke...
14,532
fig deleting node from linked list finallythe sort operation is not applicable on linked lists efficient sorting algorithms require random access to list insertion sorta ( algorithmwould workbut it would be highly inefficient if sorting were requiredit would be much more efficient to copy the linked list to randomly ac...
14,533
sequences ways to achieve the computation complexities outlined in this table either list or linked list will suffice the code in sect is an implementation of stack with list the implementation is pretty straight-forward the main program in sect tests the stack datatype with couple tests to make sure the code operates ...
14,534
trys pop(print("test failed" except runtimeerrorprint("test passed"exceptprint("test failed" trys top(print("test failed" except runtimeerrorprint("test passed"exceptprint("test failed" if __name__=="__main__"main(this codeif saved in file called stack py can be imported into other modules when this module is run by it...
14,535
sequences class queuedef __init__(self)self items [self frontidx def __compress(self)newlst [for in range(self frontidx,len(self items))newlst append(self items[ ] self items newlst self frontidx def dequeue(self)if self isempty()raise runtimeerror("attempt to dequeue an empty queue" when queue is half fullcompress it ...
14,536
for in lstq enqueue( lst [ while not isempty()lst append( dequeue() if lst !lstprint("test failed"elseprint("test passed" tryq dequeue(print("test failed" except runtimeerrorprint("test passed"exceptprint("test failed" tryq front(print("test failed" except runtimeerrorprint("test passed"exceptprint("test failed" if __n...
14,537
sequences this is certainly very interestingalbeit shortprogram the eval function does an awful lot of work for us buthow does it workit turns out we can write our own eval function using couple of stacks in this section we describe an infix expression evaluator to make our job bit easierwe'll insist that the user ente...
14,538
pop the top operator from the operator stack call this the topop if topop is +-*or then operate on the number stack by popping the operandsdoing the operationand pushing the result if topop is left paren then the given operator should be right paren if sowe are done operating and we return immediately when the preceden...
14,539
sequences fig infix evaluation step fig infix evaluation step fig infix evaluation step this copy belongs to 'acha
14,540
read from the source ( file or the internetand they are placed in queue called the mainqueue as the strings are read and placed in the queue the algorithm keeps track of the length of the longest string that will be sorted we'll call this length longest for the radix sort algorithm to work correctlyall the strings in t...
14,541
sequences queue is drawn vertically with the front of the queue being at the bottom of the box and the rear of the queue being at the top of each box while there are queues plus mainqueue created by radix sortthe example will show just the queues that are used while sorting these words the first queue in the list is th...
14,542
fig radix sort step fig radix sort step -- rd letter fig radix sort step and they all go back to the mainqueue as shown in fig no change from step in this case finallywe look at the first letter in each string and the sort is almost complete as shown in fig bringing all the strings back to the mainqueue results in the ...
14,543
sequences fig radix sort step -- nd letter fig radix sort step fig radix sort step -- st letter radix sort is pretty simple it is called radix sort because radix is like decimal point moving backwards through the string we move the decimal point one character at time until we get to the first character in each string t...
14,544
fig radix sort step summary this explored the use of linear sequences in computer programming these sequences come in many forms including randomly accessible listsmatriceslinked listsstacksand queues we also saw that two-dimensional matrix is just list of lists the also explored operations as related to these datatype...
14,545
sequences when sorting items in listwhat method must be defined for those elementswhy why does quicksort perform better than merge sort under what conditions would it be possible for merge sort to perform better than quicksort summarize what happens when list is partitioned summarize what happens when two lists are mer...
14,546
programming problems algorithm to use one extra copy of the list instead of allocating new list each time two lists are merged the extra list is allocated prior to calling the recursive part of the merge sort algorithm thenwith each alternating level of recursion the merge sort algorithm copies to the other listflippin...
14,547
sequences implement priority queue data type using linked list implementation in priority queueelements on the queue each have priority where the lower the number the higher the priority the priorities are usually just numbers the priority queue has the usual enqueuedequeueand empty methods when value is enqueued it is...
14,548
sets and maps in the last we studied sequences which are used to keep track of lists of things where duplicate values are allowed for instancethere can be two sixes in sequence or list of integers in this we look at sets where duplicate values are not allowed after examining sets we'll move on to talk about maps maps m...
14,549
sets and maps againthere will be some interesting programming problem challenges in this including optimization of the tic tac toe game first presented in the last and sudoku puzzle solver read on to discover what you need to know to solve these interesting problems playing sudoku many people enjoy solving sudoku puzzl...
14,550
fig annotated sudoku puzzle in the third row in the puzzle because those numbers already appear in other cells applying rules like these reduces the number of possible values for each cell in the puzzle figure shows the puzzle after applying some of these rules if we spend some time thinking about sudoku and how to sol...
14,551
sets and maps fig sudoku puzzle after one pass away all other values that appear in the chosen cell applying this rule to the fifth row in fig results in the fourth column being reduced to containing because does not appear in any other cell in the th row this rule also applies in the last row of the puzzle where is on...
14,552
operation set creation complexity ( set creation ( cardinality membership ( ( nonmembership disjoint ( subset (nsuperset (nunion (nintersection (nset difference (nsymmetric difference set copy (no(no(nusage =set([iterable]description calls the set constructor to create set iterable is an optional initial contents in wh...
14,553
sets and maps operation union intersection complexity (no(nusage update(ts intersection_update(tset difference symmetric difference add remove (no(no( ( difference_update(ts symmetric_difference _update(ts add(es remove(ediscard ( discard(epop clear ( ( pop( clear(description adds the contents of to updates to contain ...
14,554
be stored as string of zeroes and ones since computers speak binary these zeroes and ones can be interpreted however we likeincluding as the index into list this concept is so important that python (and many other modern languageshas included function called hash that can be called on any object to return an integer va...
14,555
sets and maps class is implemented to beginhashset objects will contain list and the number of items in the list initially the list will contain bunch of none values the list must be built with some kind of value in it none serves as null value for places in the list where no value has been stored the list isn' nearly ...
14,556
when two objects need to be stored at the same index within the hash set listbecause their computed indices are identicalwe call this collision it is necessary to define collision resolution scheme to deal with this there are many different schemes that are possible we'll explore scheme called linear probing when colli...
14,557
sets and maps the load factor the fullness of the hash set list is called its load factor we can find the load factor of hash set by dividing the number of items stored in the list by its length really small load factor means the list is much bigger than the number of items stored in it and the chance there is collisio...
14,558
hashset remove helper function class __placeholderdef __init__(self)pass def __eq__(self,other)return false def __remove(item,items)idx hash(itemlen(items while items[idx!noneif items[idx=itemnextidx (idx len(itemsif items[nextidx=noneitems[idxnone elseitems[idxhashset __placeholder(return true idx (idx len(items retur...
14,559
sets and maps hashset membership def __contains__(selfitem)idx hash(itemlen(self itemswhile self items[idx!noneif self items[idx=itemreturn true idx (idx len(self items return false finding an item results in ( amortized complexity as well the chains are kept short as long as most hash values are evenly distributed and...
14,560
hashset difference def difference(selfother)result hashset(selfresult difference_update(otherreturn result the difference method is implemented using the difference_update method on the result hashset notice that new set is returned the hash set referenced by self is not updated the code is simple and it has the added ...
14,561
sets and maps deep copy would create copy of each of the sets shallow copy of list does not copy the sets within the list calling list on list will make shallow copy another group is formed for each column and those groups are appended to the list of groups finallya group is formed for each square and those groups are ...
14,562
maps map in computer science is not like the map you used to read when going someplace in your car the term map is more mathematical term referring to function that maps domain to range you may have already used map in python maps are called by many names including dictionarieshash tablesand hash maps they are all the ...
14,563
sets and maps the hashmap class hashmap classlike the dict class in pythonuses hashing to achieve the complexities outlined in the table in fig private __kvpair class is defined instances of __kvpair hold the key/value pairs as they are added to the hashmap object with the addition of __getitem__ method on the hashset ...
14,564
thento implement the hashmap we can use hashset as shown in sect in the __kvpair class definition it is necessary to define the __eq__ method so that keys are compared when comparing two items in the hash map the __hash__ method of __kvpair hashes only the key value since keys are used to look up key/value pairs in the...
14,565
sets and maps the provided implementation in sect helps to demonstrate the similarities between the implementation of the hashset class and the hashmap classor between the set and dict classes in python the two types of data structures are both implemented using hashing both rely heavily on ( membership test while unde...
14,566
fig computing fib( as you can see from fig it takes lot of calls to the fib function to compute fib( now imagine how many calls it would take to compute fib( to compute fib( we first have to compute fib( and then compute fib( it took calls to fib to compute fib( and from the figure we can see that it takes calls to com...
14,567
sets and maps return if = memo[ return val fib( - fib( - memo[nval return val def main()print(fib( ) if __name__ ="__main__"main(the memoized fib function in sect records any value returned by the function in its memo the memo variable is accessed from the enclosing scope the memo is not created locally because we want...
14,568
summary in this we explored the implementation and some uses of sets and maps in python hashing is an important concept hashing data structures must be able to handle collisions within the hash table by collision resolution strategy the resolution strategy explored in this was linear probing there are other collision r...
14,569
sets and maps def fact( )if = return return fact( - def main() fact( print(" is",xif __name__ ="__main__"main( programming problems complete the sudoku puzzle as described in the the program should read text file prompt the user for the name of the text file the text file should be placed in the same directory or folde...
14,570
complete the hashset class found in the by implementing the methods described in the two tables of set operations thenwrite main function to test these operations save the class in file called hashset py so it can be imported into other programs if you call your main function in hashset py with the if __name__ ="__main...
14,571
trees when we see tree in our everyday lives the roots are generally in the ground and the leaves are up in the air the branches of tree spread out from the roots in more or less organized fashion the word tree is used in computer science when talking about way data may be organized trees have some similarities to the ...
14,572
trees fig the call tree for computing fib( how are expressions and trees relatedwhat is binary search treeunder what conditions is binary search tree usefulwhat is depth first search and how does it relate to trees and search problemswhat are the three types of tree traversals we can do on binary treeswhat is grammar a...
14,573
fig the ast for ( similarlynodes for the other operators and operands can be constructed to yield the tree shown in fig to represent this in the computerwe could define one class for each type of node we'll define timesnodea plusnodeand numnode class so we can evaluate the abstract syntax treeeach node in the tree will...
14,574
trees print(root eval() if __name__ ="__main__"main(in sect the tree is built from the bottom ( the leavesup to the root the code above contains an eval function for each node calling eval on the root node will recursively call eval on every node in the treecausing the result to be printed to the screen once an ast is ...
14,575
def eval(self)return self left eval(self right eval( def inorder(self)return "(self left inorder(self right inorder(") class plusnodedef __init__(selfleftright)self left left self right right def eval(self)return self left eval(self right eval( def inorder(self)return "(self left inorder(self right inorder(") class num...
14,576
trees is beyond the scope of this text howeverfor some simple expressionslike prefix expressionsit is relatively easy to build parser ourselves in middle school we learned when checking to see if sentence is properly formed we should use the english grammar grammar is set of rules that dictate how sentence in language ...
14,577
if token ="+"return plusnode( ( ), ( ) if token ="*"return timesnode( ( ), ( ) return numnode(float(token) def main() input("please enter prefix expression" lst split( queue queue( for token in lstq enqueue(token root ( print(root eval()print(root inorder() if __name__ ="__main__"main(in sect the parameter is queue of ...
14,578
trees in this grammar the first and second productions have an expression composed of an expressionfollowed by another expressionfollowed by an addition or multiplication token if we tried to write recursive function for this grammarthe base case would not come first the recursive case would come first and hence the fu...
14,579
the values in ascending order def __iter__(self)if self left !nonefor elem in self leftyield elem yield self val if self right !none for elem in self right yield elem below are the methods of the binarysearchtree class def __init__(self)self root none def insert(self,val) the __insert function is recursive and is not p...
14,580
trees enter list of numbers from this example it appears that binary search tree can produce sorted list of values when traversed howlet' examine how this program behaves with this input initiallythe tree reference points to binarysearchtree object where the root pointer points to none as shown in fig into the tree in ...
14,581
fig the tree after inserting fig the tree after inserting fig the tree after inserting nextthe is inserted into the tree as shown in fig the ended up to the right of the to preserve the binary search tree property the is inserted into the left subtree of the because is less than the is inserted next and because it is l...
14,582
trees fig the tree after inserting fig the tree after inserting to insert the it must go to the right of all nodes inserted so far since it is greater than all nodes in the tree this is depicted in fig the goes to the right of the and to the left of the in fig the only place the can go is to the right of the left of th...
14,583
fig the tree after inserting fig the tree after inserting fig the tree after inserting this copy belongs to 'acha
14,584
trees fig the final binarysearchtree object contents then the values in the right subtree are yielded by writing for elem in self right the result of this recursive function is an inorder traversal of the tree binary search trees are of some academic interest howeverthey are not used much in practice in the average cas...
14,585
solved we are seeking goal which is the solution of the puzzle we could randomly try value in cell of the puzzle and try to solve the puzzle after having made that guess the guess would lead to new state of the puzzle butif the guess were wrong we may have to go back and undo our guess wrong guess could lead to dead en...
14,586
trees reduce(matrix if not solutionviable(matrix)return none if solutionok(matrix)return matrix print("searching " for in range( )for in range( )if len(matrix[ ][ ] for in matrix[ ][ ]mcopy copy deepcopy(matrixmcopy[ ][jset([ ] result solve(mcopy if result !nonereturn result return none in the solve function of sect re...
14,587
search spaces if non-none matrix is returnedthen the puzzle is solved and the solution may be printed this is one example where no tree is ever constructedyet the search space is shaped like tree and depth first search can be used to search the problem space summary tree-like structures appear in many problems in compu...
14,588
trees describe non-recursive algorithm for doing an inorder traversal of tree hintyour algorithm will need stack to get this to work write some code to build tree for the infix expression be sure to follow the precedence of operators and in your tree you may assume the plusnode and timesnode classes from the are alread...
14,589
programming problems make choice insert into tree delete from tree lookup value choice value has been deleted from the tree make choice insert into tree delete from tree lookup value choice value was not in the tree the hardest part of this program is deleting from the tree you can write recursive function to delete va...
14,590
trees fig the tree after deleting the node containing from the tree you simply return the tree for the node containing so it ends up being linked to the node containing in fig the node containing is eliminated by making the left subtree of the node containing point at the right subtree of the node containing case this ...
14,591
programming problems complete the sudoku program as described in chap and augment it with the depth first search described in sect to complete sudoku program that is capable of solving any sudoku puzzle it should solve these puzzles almost instantly if it is taking long time to solve puzzle it is likely because your re...
14,592
graphs many problems in computer science and mathematics can be reduced to set of states and set of transitions between these states graph is mathematical representation of problems like these in the last we saw that trees serve variety of purposes in computer science trees are graphs howevergraphs are more general tha...
14,593
graphs solution we'll examine two of these algorithms called kruskal' algorithm and dijkstra' algorithmboth named for the people that formulated the algorithm to solve their respective problems graph notation little notation will help in the graph definitions in this set is an unordered collection of items for instance...
14,594
fig directed graph only in fig we can move from vertex to vertex along the edge ( , )but we cannot move from vertex to at least not without going through some other verticesbecause the edge ( , is not in the set path in graph is series of edgesnone repeatedthat can be traversed in order to travel from one vertex to ano...
14,595
graphs fig weightedundirected graph weighted graph can be used to represent the state of many different kinds of problems figure depicts weighted graph which represents roads and intersections searching graph many problems have been formulated in terms of graph theory one of the more common problems is discovering path...
14,596
fig path from vertex to vertex graphthere seems to be only one choice in most cases howeverwhen the search reaches vertex we must choose between two edges one edge takes us back to vertex which we have already visited the other edge takes us closer to the final path another choice is made at vertex if the edge to is wr...
14,597
graphs the current vertex is added to the visited set visited add(current if the current vertex is the goal vertexthen we discontinue the search reporting that we found the goal if current =goalreturn true or return path to goal perhaps otherwisefor every adjacent vertexvto the current vertex in the graphv is pushed on...
14,598
fig minimum weighted spanning tree the last introduced trees by using them in various algorithms like binary search the definition doesn' change from the last but treesin the context of graph theoryare subset of the set of all possible graphs tree is just graph without any cycles in additionit is relatively easy to pro...
14,599
graphs vertexinitially containing just that vertex that corresponds to the set in the example in fig there are initially sets each containing one vertex the algorithm proceeds as follows until | |- edges have been added to the set of spanning tree edges the next shortest edge is examined if the two vertex end points of...