id
int64
0
25.6k
text
stringlengths
0
4.59k
21,600
sub-tree with root has height and sub-tree with root has height insertion as with the red-black treeinsertion is somewhat complex and involves number of cases implementations of avl tree insertion may be found in many textbooksthey rely on adding an extra attributethe balance factor to each node this factor indicates whether the tree is left-heavy (the height of the left sub-tree is greater than the right sub-tree)balanced (both sub-trees are the same heightor right-heavy(the height of the right sub-tree is greater than the left sub-treeif the balance would be destroyed by an insertiona rotation is performed to correct the balance new item has been added to the left subtree of node causing its height to become greater than ' right subtree (shown in greena right-rotation is performed to correct the imbalance
21,601
+-tree in +-treeeach node stores up to references to children and up to keys each reference is considered "betweentwo of the node' keysit references the root of subtree for which all values are between these two keys here is fairly small tree using as our value for +-tree requires that each leaf be the same distance from the rootas in this picturewhere searching for any of the values (all listed on the bottom levelwill involve loading three nodes from the disk (the root blocka second-level blockand leafin practiced will be larger -as largein factas it takes to fill disk block suppose block is kbour keys are -byte integersand each reference is -byte file offset then we' choose to be the largest value so that ( < solving this inequality for dwe end up with < so we' use for as you can seed can be large +-tree maintains the following invariantsevery node has one more references than it has keys all leaves are at the same distance from the root for every non-leaf node with being the number of keys in nall keys in the first child' subtree are less than ' first keyand all keys in the ith child' subtree ( < <kare between the ( )th key of and the ith key of the root has at least two children every non-leafnon-root node has at least floor( children
21,602
each leaf contains at least floor( keys every key from the table appears in leafin left-to-right sorted order in our exampleswe'll continue to use for looking at our invariantsthis requires that each leaf have at least two keysand each internal node to have at least two children (and thus at least one key insertion algorithm descend to the leaf where the key fits if the node has an empty spaceinsert the key/reference pair into the node if the node is already fullsplit it into two nodesdistributing the keys evenly between the two nodes if the node is leaftake copy of the minimum value in the second of these two nodes and repeat this insertion algorithm to insert it into the parent node if the node is non-leafexclude the middle value during the split and repeat this insertion algorithm to insert this excluded value into the parent node initialinsert insert
21,603
insert insert insert deletion algorithm descend to the leaf where the key exists remove the required key and associated reference from the node if the node still has enough keys and references to satisfy the invariantsstop
21,604
youngest sibling at the same level has more than necessarydistribute the keys between this node and the neighbor repair the keys in the level above to represent that these nodes now have different "split pointbetween themthis involves simply changing key in the levels abovewithout deletion or insertion if the node has too few keys to satisfy the invariantand the next oldest or next youngest sibling is at the minimum for the invariantthen merge the node with its siblingif the node is non-leafwe will need to incorporate the "split keyfrom the parent into our merging in either casewe will need to repeat the removal algorithm on the parent node to remove the "split keythat previously separated these merged nodes -unless the parent is the root and we are removing the final key from the rootin which case the merged node becomes the new root (and the tree has become one level shorter than beforeinitialdelete
21,605
delete expression treestrees are used in many other ways in the computer science compilers and database are two major examples in this regard in case of compilerswhen the languages are translated into machine languagetree-like structures are used we have also seen an example of expression tree comprising the mathematical expression let' have more discussion on the expression trees we will see what are the benefits of expression trees and how can we build an expression tree following is the figure of an expression tree
21,606
have if you look at the figureit becomes evident that the inner nodes contain operators while leaf nodes have operands we know that there are two types of nodes in the tree inner nodes and leaf nodes the leaf nodes are such nodes which have left and right subtrees as null you will find these at the bottom level of the tree the leaf nodes are connected with the inner nodes so in treeswe have some inner nodes and some leaf nodes in the above diagramall the inner nodes (the nodes which have either left or right child or bothhave operators in this casewe have or as operators whereas leaf nodes contain operands only abcdefg this tree is binary as the operators are binary we have discussed the evaluation of postfix and infix expressions and have seen that the binary operators need two operands in the infix expressionsone operand is on the left side of the operator and the other is on the right side supposeif we have operatorit will be written as howeverin case of multiplicationwe will write as * we may have unary operators like negation (-or in boolean expression we have not in this examplethere are all the binary operators thereforethis tree is binary tree this is not the binary search tree in bstthe values on the left side of the nodes are smaller and the values on the right side are greater than the node thereforethis is not bst here we have an expression tree with no sorting process involved this is not necessary that expression tree is always binary tree suppose we have unary operator like negation in this casewe have node which has (-in it and there is only one leaf node under it it means just negate that operand let' talk about the traversal of the expression tree the inorder traversal may be executed here
21,607
binary search tree (bsta binary search tree (bstis tree in which all the nodes follow the below-mentioned properties the left sub-tree of node has key less than or equal to its parent node' key the right sub-tree of node has key greater than to its parent node' key thusbst divides all its sub-trees into two segmentsthe left sub-tree and the right sub-tree and can be defined as left_subtree (keys<node (key<right_subtree (keysrepresentation bst is collection of nodes arranged in way where they maintain bst properties each node has key and an associated value while searchingthe desired key is compared to the keys in bst and if foundthe associated value is retrieved following is pictorial representation of bst we observe that the root node key ( has all less-valued keys on the left sub-tree and the higher valued keys on the right sub-tree basic operations following are the basic operations of tree search searches an element in tree insert inserts an element in tree pre-order traversal traverses tree in pre-order manner in-order traversal traverses tree in an in-order manner post-order traversal traverses tree in post-order manner node
21,608
struct node int datastruct node *leftchildstruct node *rightchild}search operation whenever an element is to be searchedstart searching from the root node then if the data is less than the key valuesearch for the element in the left subtree otherwisesearch for the element in the right subtree follow the same algorithm for each node algorithm struct nodesearch(int data)struct node *current rootprintf("visiting elements")while(current->data !data)if(current !nullprintf("% ",current->data)//go to left tree if(current->data data)current current->leftchild//else go to right tree else current current->rightchild//not found
21,609
return nullreturn currentinsert operation whenever an element is to be insertedfirst locate its proper location start searching from the root nodethen if the data is less than the key valuesearch for the empty location in the left subtree and insert the data otherwisesearch for the empty location in the right subtree and insert the data algorithm void insert(int datastruct node *tempnode (struct node*malloc(sizeof(struct node))struct node *currentstruct node *parenttempnode->data datatempnode->leftchild nulltempnode->rightchild null//if tree is empty if(root =nullroot tempnodeelse current rootparent null
21,610
parent current//go to left of the tree if(data datacurrent current->leftchild//insert to the left if(current =nullparent->leftchild tempnodereturn//go to right of the tree else current current->rightchild//insert to the right if(current =nullparent->rightchild tempnodereturn
21,611
lecture- graphs terminology graph consists ofa setvof vertices (nodesa collectioneof pairs of vertices from called edges (arcsedgesalso called arcsare represented by (uvand are eitherdirected if the pairs are ordered (uvu the origin the destination undirected if the pairs are unordered graph is pictorial representation of set of objects where some pairs of objects are connected by links the interconnected objects are represented by points termed as verticesand the links that connect the vertices are called edges formallya graph is pair of sets (ve)where is the set of vertices and eis the set of edgesconnecting the pairs of vertices take look at the following graph in the above graphv {abcdee {abacbdcddethen graph can bedirected graph (di-graphif all the edges are directed undirected graph (graphif all the edges are undirected mixed graph if edges are both directed or undirected illustrate terms on graphs end-vertices of an edge are the endpoints of the edge two vertices are adjacent if they are endpoints of the same edge an edge is incident on vertex if the vertex is an endpoint of the edge outgoing edges of vertex are directed edges that the vertex is the origin incoming edges of vertex are directed edges that the vertex is the destination degree of vertexvdenoted deg(vis the number of incident edges out-degreeoutdeg( )is the number of outgoing edges in-degreeindeg( )is the number of incoming edges parallel edges or multiple edges are edges of the same type and end-vertices self-loop is an edge with the end vertices the same vertex
21,612
properties if graphghas edges then svg deg( if di-graphghas edges then svg indeg(vm svg outdeg(vif simple graphghas edges and verticesif is also directed then < ( - if is also undirected then < ( - )/ so simple graph with vertices has ( edges at most more terminology path is sequence of alternating vetches and edges such that each successive vertex is connected by the edge frequently only the vertices are listed especially if there are no parallel edges cycle is path that starts and end at the same vertex simple path is path with distinct vertices directed path is path of only directed edges directed cycle is cycle of only directed edges sub-graph is subset of vertices and edges spanning sub-graph contains all the vertices connected graph has all pairs of vertices connected by at least one path connected component is the maximal connected sub-graph of unconnected graph forest is graph without cycles tree is connected forest (previous type of trees are called rooted treesthese are free treesspanning tree is spanning subgraph that is also tree more properties if is an undirected graph with vertices and edgesif is connected then > if is tree then if is forest then < graph traversal depth first search breadth first search
21,613
depth first searchdepth first search (dfsalgorithm traverses graph in depthward motion and uses stack to remember to get the next vertex to start searchwhen dead end occurs in any iteration as in the example given abovedfs algorithm traverses from to to to to to firstthen to and lastly to it employs the following rules rule visit the adjacent unvisited vertex mark it as visited display it push it in stack rule if no adjacent vertex is foundpop up vertex from the stack (it will pop up all the vertices from the stackwhich do not have adjacent vertices rule repeat rule and rule until the stack is empty step traversal description initialize the stack
21,614
mark as visited and put it onto the stack explore any unvisited adjacent node from we have three nodes and we can pick any of them for this examplewe shall take the node in an alphabetical order mark as visited and put it onto the stack explore any unvisited adjacent node from both sand are adjacent to but we are concerned for unvisited nodes only visit and mark it as visited and put onto the stack herewe have and nodeswhich are adjacent to and both are unvisited howeverwe shall again choose in an alphabetical order we choose bmark it as visited and put onto the stack here bdoes not have any unvisited adjacent node sowe pop bfrom the stack
21,615
we check the stack top for return to the previous node and check if it has any unvisited nodes herewe find to be on the top of the stack only unvisited adjacent node is from is now so we visit cmark it as visited and put it onto the stack as does not have any unvisited adjacent node so we keep popping the stack until we find node that has an unvisited adjacent node in this casethere' none and we keep popping until the stack is empty
21,616
breadth first search breadth first search (bfsalgorithm traverses graph in breadthward motion and uses queue to remember to get the next vertex to start searchwhen dead end occurs in any iteration as in the example given abovebfs algorithm traverses from to to to first then to and lastly to it employs the following rules rule visit the adjacent unvisited vertex mark it as visited display it insert it in queue rule if no adjacent vertex is foundremove the first vertex from the queue rule repeat rule and rule until the queue is empty step traversal description initialize the queue
21,617
we start from visiting (starting node)and mark it as visited we then see an unvisited adjacent node from in this examplewe have three nodes but alphabetically we choose amark it as visited and enqueue it nextthe unvisited adjacent node from is we mark it as visited and enqueue it nextthe unvisited adjacent node from is we mark it as visited and enqueue it
21,618
nows is left with no unvisited adjacent nodes sowe dequeue and find from we have as unvisited adjacent node we mark it as visited and enqueue it at this stagewe are left with no unmarked (unvisitednodes but as per the algorithm we keep on dequeuing in order to get all unvisited nodes when the queue gets emptiedthe program is over
21,619
graph representation you can represent graph in many ways the two most common ways of representing graph is as followsadjacency matrix an adjacency matrix is vxv binary matrix element ai, is if there is an edge from vertex to vertex else ai,jis notea binary matrix is matrix in which the cells can have only one of two possible values either or the adjacency matrix can also be modified for the weighted graph in which instead of storing or in ai,jthe weight or cost of the edge will be stored in an undirected graphif ai, then aj, in directed graphif ai, then aj, may or may not be adjacency matrix provides constant time access ( ( to determine if there is an edge between two nodes space complexity of the adjacency matrix is ( the adjacency matrix of the following graph isi/ : : : : the adjacency matrix of the following graph isi/ : : : :
21,620
the other way to represent graph is by using an adjacency list an adjacency list is an array of separate lists each element of the array ai is listwhich contains all the vertices that are adjacent to vertex for weighted graphthe weight or cost of the edge is stored along with the vertex in the list using pairs in an undirected graphif vertex is in list ai then vertex will be in list aj the space complexity of adjacency list is ( ebecause in an adjacency list information is stored only for those edges that actually exist in the graph in lot of caseswhere matrix is sparse using an adjacency matrix may not be very useful this is because using an adjacency matrix will take up lot of space where most of the elements will be anyway in such casesusing an adjacency list is better notea sparse matrix is matrix in which most of the elements are zerowhereas dense matrix is matrix in which most of the elements are non-zero consider the same undirected graph from an adjacency matrix the adjacency list of the graph is as followsa
21,621
consider the same directed graph from an adjacency matrix the adjacency list of the graph is as followsa
21,622
topological sortingtopological sorting for directed acyclic graph (dagis linear ordering of vertices such that for every directed edge uvvertex comes before in the ordering topological sorting for graph is not possible if the graph is not dag for examplea topological sorting of the following graph is " there can be more than one topological sorting for graph for exampleanother topological sorting of the following graph is " the first vertex in topological sorting is always vertex with in-degree as ( vertex with no in-coming edgesalgorithm to find topological sortingin dfswe start from vertexwe first print it and then recursively call dfs for its adjacent vertices in topological sortingwe use temporary stack we don' print the vertex immediatelywe first recursively call topological sorting for all its adjacent verticesthen push it to stack finallyprint contents of stack note that vertex is pushed to stack only when all of its adjacent vertices (and their adjacent vertices and so onare already in stack topological sorting vs depth first traversal (dfs)in dfswe print vertex and then recursively call dfs for its adjacent vertices in topological sortingwe need to print vertex before its adjacent vertices for examplein the given graphthe vertex ' should be printed before vertex ' 'but unlike dfsthe vertex ' should also be printed before vertex ' so topological sorting is different from dfs for examplea dfs of the shown graph is " "but it is not topological sorting dynamic programming the floyd warshall algorithm is for solving the all pairs shortest path problem the problem is to find shortest distances between every pair of vertices in given edge weighted directed graph exampleinputgraph[][{ inf }{inf inf}{infinf }{infinfinf which represents the following graph
21,623
/| | \|( )>( note that the value of graph[ ][jis if is equal to and graph[ ][jis inf (infiniteif there is no edge from vertex to outputshortest distance matrix inf inf inf inf inf inf floyd warshall algorithm we initialize the solution matrix same as the input graph matrix as first step then we update the solution matrix by considering all vertices as an intermediate vertex the idea is to one by one pick all vertices and update all shortest paths which include the picked vertex as an intermediate vertex in the shortest path when we pick vertex number as an intermediate vertexwe already have considered vertices { - as intermediate vertices for every pair (ijof source and destination vertices respectivelythere are two possible cases is not an intermediate vertex in shortest path from to we keep the value of dist[ ][jas it is is an intermediate vertex in shortest path from to we update the value of dist[ ][jas dist[ ][kdist[ ][jthe following figure shows the above optimal substructure property in the all-pairs shortest path problem
21,624
bubble sort we take an unsorted array for our example bubble sort takes ( time so we're keeping it short and precise bubble sort starts with very first two elementscomparing them to check which one is greater in this casevalue is greater than so it is already in sorted locations nextwe compare with we find that is smaller than and these two values must be swapped the new array should look like this next we compare and we find that both are in already sorted positions then we move to the next two values and we know then that is smaller hence they are not sorted we swap these values we find that we have reached the end of the array after one iterationthe array should look like this to be precisewe are now showing how an array should look like after each iteration after the second iterationit should look like this
21,625
and when there' no swap requiredbubble sorts learns that an array is completely sorted now we should look into some practical aspects of bubble sort algorithm we assume list is an array of elements we further assume that swapfunction swaps the values of the given array elements begin bubblesort(listfor all elements of list if list[ilist[ + swap(list[ ]list[ + ]end if end for return list end bubblesort pseudocode we observe in algorithm that bubble sort compares each pair of array element unless the whole array is completely sorted in an ascending order this may cause few complexity issues like what if the array needs no more swapping as all the elements are already ascending to ease-out the issuewe use one flag variable swapped which will help us see if any swap has happened or not if no swap has occurredi the array requires no more processing to be sortedit will come out of the loop pseudocode of bubblesort algorithm can be written as follows procedure bubblesortlist array of items loop list countfor to loop- doswapped false
21,626
/compare the adjacent elements *if list[jlist[ + then /swap them *swaplist[ ]list[ + swapped true end if end for /*if no number was swapped that means array is sorted nowbreak the loop *if(not swappedthen break end if end for end procedure return list
21,627
insertion sort we take an unsorted array for our example insertion sort compares the first two elements it finds that both and are already in ascending order for now is in sorted sub-list insertion sort moves ahead and compares with and finds that is not in the correct position it swaps with it also checks with all the elements of sorted sub-list here we see that the sorted sub-list has only one element and is greater than hencethe sorted sub-list remains sorted after swapping by now we have and in the sorted sub-list nextit compares with these values are not in sorted order so we swap them howeverswapping makes and unsorted
21,628
again we find and in an unsorted order we swap them again by the end of third iterationwe have sorted sub-list of items this process goes on until all the unsorted values are covered in sorted sub-list now we shall see some programming aspects of insertion sort algorithm now we have bigger picture of how this sorting technique worksso we can derive simple steps by which we can achieve insertion sort step if it is the first elementit is already sorted return step pick next element step compare with all elements in the sorted sub-list step shift all the elements in the sorted sub-list that is greater than the value to be sorted step insert the value step repeat until list is sorted pseudocode procedure insertionsorta array of items int holeposition int valuetoinsert for to length(ainclusive dovaluetoinsert [iholeposition while holeposition and [holeposition- valuetoinsert doa[holepositiona[holeposition- holeposition holeposition - end while [holepositionvaluetoinsert end for end procedure
21,629
selection sort consider the following depicted array as an example for the first position in the sorted listthe whole list is scanned sequentially the first position where is stored presentlywe search the whole list and find that is the lowest value so we replace with after one iteration which happens to be the minimum value in the listappears in the first position of the sorted list for the second positionwhere is residingwe start scanning the rest of the list in linear manner we find that is the second lowest value in the list and it should appear at the second place we swap these values after two iterationstwo least values are positioned at the beginning in sorted manner the same process is applied to the rest of the items in the array following is pictorial depiction of the entire sorting process
21,630
algorithm step set min to location step search the minimum element in the list step swap with value at location min step increment min to point to next element step repeat until list is sorted
21,631
procedure selection sort list array of items size of list for to /set current element as minimum*min /check the element to be minimum *for + to if list[jlist[minthen min jend if end for /swap the minimum element with the current element*if indexmin ! then swap list[minand list[iend if end for end procedure
21,632
merge sort to understand merge sortwe take an unsorted array as the following we know that merge sort first divides the whole array iteratively into equal halves unless the atomic values are achieved we see here that an array of items is divided into two arrays of size this does not change the sequence of appearance of items in the original now we divide these two arrays into halves we further divide these arrays and we achieve atomic value which can no more be divided nowwe combine them in exactly the same manner as they were broken down please note the color codes given to these lists we first compare the element for each list and then combine them into another list in sorted manner we see that and are in sorted positions we compare and and in the target list of values we put firstfollowed by we change the order of and whereas and are placed sequentially in the next iteration of the combining phasewe compare lists of two data valuesand merge them into list of found data values placing all in sorted order after the final mergingthe list should look like this now we should learn some programming aspects of merge sorting algorithm
21,633
by definitionif it is only one element in the listit is sorted thenmerge sort combines the smaller sorted lists keeping the new list sorted too step if it is only one element in the list it is already sortedreturn step divide the list recursively into two halves until it can no more be divided step merge the smaller lists into new list in sorted order merge sort works with recursion and we shall see our implementation in the same way procedure mergesortvar as array if = return var as array [ [ / var as array [ / + [nl mergesortl mergesortl return mergel end procedure procedure mergevar as arrayvar as array var as array while and have elements if [ [ add [ to the end of remove [ from else add [ to the end of remove [ from end if end while while has elements add [ to the end of remove [ from end while while has elements add [ to the end of remove [ from end while return end procedure
21,634
quick sort quick sort is highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays large array is partitioned into two arrays one of which holds values smaller than the specified valuesay pivotbased on which the partition is made and another array holds values greater than the pivot value quick sort partitions an array and then calls itself recursively twice to sort the two resulting subarrays this algorithm is quite efficient for large-sized data sets as its average and worst case complexity are of ( )where is the number of items partition in quick sort following animated representation explains how to find the pivot value in an array the pivot value divides the list into two parts and recursivelywe find the pivot for each sub-lists until all lists contains only one element quick sort pivot algorithm based on our understanding of partitioning in quick sortwe will now try to write an algorithm for itwhich is as follows step choose the highest index value has pivot step take two variables to point left and right of the list excluding pivot step left points to the low index step right points to the high step while value at left is less than pivot move right step while value at right is greater than pivot move left step if both step and step does not match swap left and right step if left >rightthe point where they met is new pivot quick sort pivot pseudocode the pseudocode for the above algorithm can be derived as function partitionfunc(leftrightpivotleftpointer left rightpointer right while true do while [++leftpointerpivot do
21,635
end while while rightpointer & [--rightpointerpivot do //do-nothing end while if leftpointer >rightpointer break else swap leftpointer,rightpointer end if end while swap leftpointer,right return leftpointer end function quick sort algorithm using pivot algorithm recursivelywe end up with smaller possible partitions each partition is then processed for quick sort we define recursive algorithm for quicksort as follows step make the right-most index value pivot step partition the array using pivot value step quicksort left partition recursively step quicksort right partition recursively quick sort pseudocode to get more into itlet see the pseudocode for quick sort algorithm procedure quicksort(leftrightif right-left < return else pivot [rightpartition partitionfunc(leftrightpivotquicksort(left,partition- quicksort(partition+ ,rightend if end procedure
21,636
heap sort heap sort is comparison based sorting technique based on binary heap data structure it is similar to selection sort where we first find the maximum element and place the maximum element at the end we repeat the same process for remaining element what is binary heaplet us first define complete binary tree complete binary tree is binary tree in which every levelexcept possibly the lastis completely filledand all nodes are as far left as possible binary heap is complete binary tree where items are stored in special order such that value in parent node is greater(or smallerthan the values in its two children nodes the former is called as max heap and the latter is called min heap the heap can be represented by binary tree or array why array based representation for binary heapsince binary heap is complete binary treeit can be easily represented as array and array based representation is space efficient if the parent node is stored at index ithe left child can be calculated by and right child by (assuming the indexing starts at heap sort algorithm for sorting in increasing order build max heap from the input data at this pointthe largest item is stored at the root of the heap replace it with the last item of the heap followed by reducing the size of heap by finallyheapify the root of tree repeat above steps while size of heap is greater than how to build the heapheapify procedure can be applied to node only if its children nodes are heapified so the heapification must be performed in the bottom up order lets understand with the help of an exampleinput data ( ( ( ( ( the numbers in bracket represent the indices in the array representation of data
21,637
( ( ( ( ( applying heapify procedure to index ( ( ( ( ( the heapify procedure calls itself recursively to build heap in top down manner radix sort the lower bound for comparison based sorting algorithm (merge sortheap sortquick-sort etcis (nlogn) they cannot do better than nlogn counting sort is linear time sorting algorithm that sort in ( +ktime when elements are in range from to what if the elements are in range from to we can' use counting sort because counting sort will take ( which is worse than comparison based sorting algorithms can we sort such an array in linear timeradix sort is the answer the idea of radix sort is to do digit by digit sort starting from least significant digit to most significant digit radix sort uses counting sort as subroutine to sort
21,638
radix sort do following for each digit where varies from least significant digit to the most significant digit asort input array using counting sort (or any stable sortaccording to the 'th digit exampleoriginalunsorted list sorting by least significant digit ( placegives[*notice that we keep before because occurred before in the original listand similarly for pairs and sorting by next digit ( placegives[*notice that again comes before as comes before in the previous list sorting by most significant digit ( placegives what is the running time of radix sortlet there be digits in input integers radix sort takes ( *( + )time where is the base for representing numbersfor examplefor decimal systemb is what is the value of dif is the maximum possible valuethen would be (log ( )so overall time complexity is (( +blogb( )which looks more than the time complexity of comparison based sorting algorithms for large let us first limit let <nc where is constant in that casethe complexity becomes (nlog ( )but it still doesn' beat comparison based sorting algorithms linear search linear search is to check each element one by one in sequence the following method linearsearch(searches target in an array and returns the index of the targetif not foundit returns - which indicates an invalid index int linearsearch(int arr[]int target for (int arr lengthi++ if (arr[ =target return return -
21,639
time thereforeit runs in linear time (nlecture- binary search for sorted arraysbinary search is more efficient than linear search the process starts from the middle of the input arrayif the target equals the element in the middlereturn its index if the target is larger than the element in the middlesearch the right half if the target is smallersearch the left half in the following binarysearch(methodthe two index variables first and last indicates the searching boundary at each round int binarysearch(int arr[]int target int first last arr length while (first <last int mid (first last if (target =arr[mid] return mid if (target arr[mid] first mid else last mid return - arr{ target first last mid arr[mid] -go left first last mid arr[mid] -go right first last mid arr[mid] -found target first last mid arr[mid] -go right first last mid arr[mid] -go left first last mid arr[mid] -go right first last -not found
21,640
the design and analysis of efficient data structures has long been recognized as vital subject in computing and is part of the core curriculum of computer science and computer engineering undergraduate degrees data structures and algorithms in python provides an introduction to data structures and algorithmsincluding their designanalysisand implementation this book is designed for use in beginninglevel data structures courseor in an intermediate-level introduction to algorithms course we discuss its use for such courses in more detail later in this preface to promote the development of robust and reusable softwarewe have tried to take consistent object-oriented viewpoint throughout this text one of the main ideas of the object-oriented approach is that data should be presented as being encapsulated with the methods that access and modify them that israther than simply viewing data as collection of bytes and addresseswe think of data objects as instances of an abstract data type (adt)which includes repertoire of methods for performing operations on data objects of this type we then emphasize that there may be several different implementation strategies for particular adtand explore the relative pros and cons of these choices we provide complete python implementations for almost all data structures and algorithms discussedand we introduce important object-oriented design patterns as means to organize those implementations into reusable components desired outcomes for readers of our book include thatthey have knowledge of the most common abstractions for data collections ( stacksqueuesliststreesmapsthey understand algorithmic strategies for producing efficient realizations of common data structures they can analyze algorithmic performanceboth theoretically and experimentallyand recognize common trade-offs between competing strategies they can wisely use existing data structures and algorithms found in modern programming language libraries they have experience working with concrete implementations for most foundational data structures and algorithms they can apply data structures and algorithms to solve complex problems in support of the last goalwe present many example applications of data structures throughout the bookincluding the processing of file systemsmatching of tags in structured formats such as htmlsimple cryptographytext frequency analysisautomated geometric layouthuffman codingdna sequence alignmentand search engine indexing
21,641
vi book features this book is based upon the book data structures and algorithms in java by goodrich and tamassiaand the related data structures and algorithms in +by goodrichtamassiaand mount howeverthis book is not simply translation of those other books to python in adapting the material for this bookwe have significantly redesigned the organization and content of the book as followsthe code base has been entirely redesigned to take advantage of the features of pythonsuch as use of generators for iterating elements of collection many algorithms that were presented as pseudo-code in the java and +versions are directly presented as complete python code in generaladts are defined to have consistent interface with python' builtin data types and those in python' collections module provides an in-depth exploration of the dynamic array-based underpinnings of python' built-in listtupleand str classes new appendix serves as an additional reference regarding the functionality of the str class over illustrations have been created or revised new and revised exercises bring the overall total number to online resources this book is accompanied by an extensive set of online resourceswhich can be found at the following web sitewww wiley com/college/goodrich students are encouraged to use this site along with the bookto help with exercises and increase understanding of the subject instructors are likewise welcome to use the site to help planorganizeand present their course materials included on this web site is collection of educational aids that augment the topics of this bookfor both students and instructors because of their added valuesome of these online resources are password protected for all readersand especially for studentswe include the following resourcesall the python source code presented in this book pdf handouts of powerpoint slides (four-per-pageprovided to instructors database of hints to all exercisesindexed by problem number for instructors using this bookwe include the following additional teaching aidssolutions to hundreds of the book' exercises color versions of all figures and illustrations from the book slides in powerpoint and pdf (one-per-pageformat the slides are fully editableso as to allow an instructor using this book full freedom in customizing his or her presentations all the online resources are provided at no extra charge to any instructor adopting this book for his or her course
21,642
vii contents and organization the for this book are organized to provide pedagogical path that starts with the basics of python programming and object-oriented design we then add foundational techniques like algorithm analysis and recursion in the main portion of the bookwe present fundamental data structures and algorithmsconcluding with discussion of memory management (that isthe architectural underpinnings of data structuresspecificallythe for this book are organized as follows python primer object-oriented programming algorithm analysis recursion array-based sequences stacksqueuesand deques linked lists trees priority queues mapshash tablesand skip lists search trees sorting and selection text processing graph algorithms memory management and -trees character strings in python useful mathematical facts more detailed table of contents follows this prefacebeginning on page xi prerequisites we assume that the reader is at least vaguely familiar with high-level programming languagesuch as cc++pythonor javaand that he or she understands the main constructs from such high-level languageincludingvariables and expressions decision structures (such as if-statements and switch-statementsiteration structures (for loops and while loopsfunctions (whether stand-alone or object-oriented methodsfor readers who are familiar with these conceptsbut not with how they are expressed in pythonwe provide primer on the python language in stillthis book is primarily data structures booknot python bookhenceit does not give comprehensive treatment of python
21,643
viii we delay treatment of object-oriented programming in python until this is useful for those new to pythonand for those who may be familiar with pythonyet not with object-oriented programming in terms of mathematical backgroundwe assume the reader is somewhat familiar with topics from high-school mathematics even soin we discuss the seven most-important functions for algorithm analysis in factsections that use something other than one of these seven functions are considered optionaland are indicated with star (we give summary of other useful mathematical factsincluding elementary probabilityin appendix relation to computer science curriculum to assist instructors in designing course in the context of the ieee/acm computing curriculumthe following table describes curricular knowledge units that are covered within this book knowledge unit al/basic analysis al/algorithmic strategies al/fundamental data structures and algorithms al/advanced data structures ar/memory system organization and architecture ds/setsrelations and functions ds/proof techniques ds/basics of counting ds/graphs and trees ds/discrete probability pl/object-oriented programming pl/functional programming sdf/algorithms and design sdf/fundamental programming concepts sdf/fundamental data structures sdf/developmental methods se/software design relevant material and sections sections sections much of sections through sections sections sections appendix much of and sections much of the bookyet especially and sections section sections appendix aand sections sections sections mapping ieee/acm computing curriculum knowledge units to coverage in this book
21,644
ix about the authors michael goodrich received his ph in computer science from purdue university in he is currently chancellor' professor in the department of computer science at university of californiairvine previouslyhe was professor at johns hopkins university he is fulbright scholar and fellow of the american association for the advancement of science (aaas)association for computing machinery (acm)and institute of electrical and electronics engineers (ieeehe is recipient of the ieee computer society technical achievement awardthe acm recognition of service awardand the pond award for excellence in undergraduate teaching roberto tamassia received his ph in electrical and computer engineering from the university of illinois at urbana-champaign in he is the plastech professor of computer science and the chair of the department of computer science at brown university he is also the director of brown' center for geometric computing his research interests include information securitycryptographyanalysisdesignand implementation of algorithmsgraph drawing and computational geometry he is fellow of the american association for the advancement of science (aaas)association for computing machinery (acmand institute for electrical and electronic engineers (ieeehe is also recipient of the technical achievement award from the ieee computer society michael goldwasser received his ph in computer science from stanford university in he is currently professor in the department of mathematics and computer science at saint louis university and the director of their computer science program previouslyhe was faculty member in the department of computer science at loyola university chicago his research interests focus on the design and implementation of algorithmshaving published work involving approximation algorithmsonline computationcomputational biologyand computational geometry he is also active in the computer science education community additional books by these authors goodrich and tamassiadata structures and algorithms in javawiley goodrichr tamassiaand mountdata structures and algorithms in ++wiley goodrich and tamassiaalgorithm designfoundationsanalysisand internet exampleswiley goodrich and tamassiaintroduction to computer securityaddisonwesley goldwasser and letscherobject-oriented programming in pythonprentice hall
21,645
acknowledgments we have depended greatly upon the contributions of many individuals as part of the development of this book we begin by acknowledging the wonderful team at wiley we are grateful to our editorbeth golubfor her enthusiastic support of this projectfrom beginning to end the efforts of elizabeth mills and katherine willis were critical in keeping the project movingfrom its early stages as an initial proposalthrough the extensive peer review process we greatly appreciate the attention to detail demonstrated by julie kennedythe copyeditor for this book finallymany thanks are due to joyce poh for managing the final months of the production process we are truly indebted to the outside reviewers and readers for their copious commentsemailsand constructive criticismwhich were extremely useful in writing this edition we therefore thank the following reviewers for their comments and suggestionsclaude anderson (rose hulman institute of technology)alistair campbell (hamilton college)barry cohen (new jersey institute of technology)robert franks (central college)andrew harrington (loyola university chicago)dave musicant (carleton college)and victor norman (calvin collegewe wish to particularly acknowledge claude for going above and beyond the call of dutyproviding us with an enumeration of detailed corrections or suggestions we thank david mountof university of marylandfor graciously sharing the wisdom gained from his experience with the +version of this text we are grateful to erin chambers and david letscherof saint louis universityfor their intangible contributions during many hallway conversations about the teaching of data structuresand to david for comments on early versions of the python code base for this book we thank david zampinoa student at loyola university chicagofor his feedback while using draft of this book during an independent study courseand to andrew harrington for supervising david' studies we also wish to reiterate our thanks to the many research collaborators and teaching assistants whose feedback shaped the previous java and +versions of this material the benefits of those contributions carry forward to this book finallywe would like to warmly thank susan goldwasserisabel cruzkaren goodrichgiuseppe di battistafranco preparataioannis tollisand our parents for providing adviceencouragementand support at various stages of the preparation of this bookand calista and maya goldwasser for offering their advice regarding the artistic merits of many illustrations more importantlywe thank all of these people for reminding us that there are things in life beyond writing books michael goodrich roberto tamassia michael goldwasser
21,646
preface python primer python overview the python interpreter preview of python program objects in python identifiersobjectsand the assignment statement creating and using objects python' built-in classes expressionsoperatorsand precedence compound expressions and operator precedence control flow conditionals loops functions information passing python' built-in functions simple input and output console input and output files exception handling raising an exception catching an exception iterators and generators additional python conveniences conditional expressions comprehension syntax packing and unpacking of sequences scopes and namespaces modules and the import statement existing modules exercises xi
21,647
contents object-oriented programming goalsprinciplesand patterns object-oriented design goals object-oriented design principles design patterns software development design pseudo-code coding style and documentation testing and debugging class definitions examplecreditcard class operator overloading and python' special methods examplemultidimensional vector class iterators examplerange class inheritance extending the creditcard class hierarchy of numeric progressions abstract base classes namespaces and object-orientation instance and class namespaces name resolution and dynamic dispatch shallow and deep copying exercises algorithm analysis experimental studies moving beyond experimental analysis the seven functions used in this book comparing growth rates asymptotic analysis the "big-ohnotation comparative analysis examples of algorithm analysis simple justification techniques by example the "contraattack induction and loop invariants exercises
21,648
xiii recursion illustrative examples the factorial function drawing an english ruler binary search file systems analyzing recursive algorithms recursion run amok maximum recursive depth in python further examples of recursion linear recursion binary recursion multiple recursion designing recursive algorithms eliminating tail recursion exercises array-based sequences python' sequence types low-level arrays referential arrays compact arrays in python dynamic arrays and amortization implementing dynamic array amortized analysis of dynamic arrays python' list class efficiency of python' sequence types python' list and tuple classes python' string class using array-based sequences storing high scores for game sorting sequence simple cryptography multidimensional data sets exercises stacksqueuesand deques stacks the stack abstract data type simple array-based stack implementation reversing data using stack matching parentheses and html tags
21,649
contents queues the queue abstract data type array-based queue implementation double-ended queues the deque abstract data type implementing deque with circular array deques in the python collections module exercises linked lists singly linked lists implementing stack with singly linked list implementing queue with singly linked list circularly linked lists round-robin schedulers implementing queue with circularly linked list doubly linked lists basic implementation of doubly linked list implementing deque with doubly linked list the positional list adt the positional list abstract data type doubly linked list implementation sorting positional list case studymaintaining access frequencies using sorted list using list with the move-to-front heuristic link-based vs array-based sequences exercises trees general trees tree definitions and properties the tree abstract data type computing depth and height binary trees the binary tree abstract data type properties of binary trees implementing trees linked structure for binary trees array-based representation of binary tree linked structure for general trees tree traversal algorithms
21,650
xv preorder and postorder traversals of general trees breadth-first tree traversal inorder traversal of binary tree implementing tree traversals in python applications of tree traversals euler tours and the template method pattern case studyan expression tree exercises priority queues the priority queue abstract data type priorities the priority queue adt implementing priority queue the composition design pattern implementation with an unsorted list implementation with sorted list heaps the heap data structure implementing priority queue with heap array-based representation of complete binary tree python heap implementation analysis of heap-based priority queue bottom-up heap construction python' heapq module sorting with priority queue selection-sort and insertion-sort heap-sort adaptable priority queues locators implementing an adaptable priority queue exercises mapshash tablesand skip lists maps and dictionaries the map adt applicationcounting word frequencies python' mutablemapping abstract base class our mapbase class simple unsorted map implementation hash tables hash functions
21,651
contents collision-handling schemes load factorsrehashingand efficiency python hash table implementation sorted maps sorted search tables two applications of sorted maps skip lists search and update operations in skip list probabilistic analysis of skip lists setsmultisetsand multimaps the set adt python' mutableset abstract base class implementing setsmultisetsand multimaps exercises search trees binary search trees navigating binary search tree searches insertions and deletions python implementation performance of binary search tree balanced search trees python framework for balancing search trees avl trees update operations python implementation splay trees splaying when to splay python implementation amortized analysis of splaying ( , trees multiway search trees ( , )-tree operations red-black trees red-black tree operations python implementation exercises
21,652
xvii sorting and selection why study sorting algorithms merge-sort divide-and-conquer array-based implementation of merge-sort the running time of merge-sort merge-sort and recurrence equations alternative implementations of merge-sort quick-sort randomized quick-sort additional optimizations for quick-sort studying sorting through an algorithmic lens lower bound for sorting linear-time sortingbucket-sort and radix-sort comparing sorting algorithms python' built-in sorting functions sorting according to key function selection prune-and-search randomized quick-select analyzing randomized quick-select exercises text processing abundance of digitized text notations for strings and the python str class pattern-matching algorithms brute force the boyer-moore algorithm the knuth-morris-pratt algorithm dynamic programming matrix chain-product dna and text sequence alignment text compression and the greedy method the huffman coding algorithm the greedy method tries standard tries compressed tries suffix tries search engine indexing
21,653
contents exercises graph algorithms graphs the graph adt data structures for graphs edge list structure adjacency list structure adjacency map structure adjacency matrix structure python implementation graph traversals depth-first search dfs implementation and extensions breadth-first search transitive closure directed acyclic graphs topological ordering shortest paths weighted graphs dijkstra' algorithm minimum spanning trees prim-jarnik algorithm kruskal' algorithm disjoint partitions and union-find structures exercises memory management and -trees memory management memory allocation garbage collection additional memory used by the python interpreter memory hierarchies and caching memory systems caching strategies external searching and -trees ( ,btrees -trees external-memory sorting multiway merging exercises
21,654
xix character strings in python useful mathematical facts bibliography index
21,655
python primer contents python overview the python interpreter preview of python program objects in python identifiersobjectsand the assignment statement creating and using objects python' built-in classes expressionsoperatorsand precedence compound expressions and operator precedence control flow conditionals loops functions information passing python' built-in functions simple input and output console input and output files exception handling raising an exception catching an exception iterators and generators additional python conveniences conditional expressions comprehension syntax packing and unpacking of sequences scopes and namespaces modules and the import statement existing modules exercises
21,656
python overview building data structures and algorithms requires that we communicate detailed instructions to computer an excellent way to perform such communications is using high-level computer languagesuch as python the python programming language was originally developed by guido van rossum in the early sand has since become prominently used language in industry and education the second major version of the languagepython was released in and the third major versionpython released in we note that there are significant incompatibilities between python and python this book is based on python (more specificallypython or laterthe latest version of the language is freely available at www python orgalong with documentation and tutorials in this we provide an overview of the python programming languageand we continue this discussion in the next focusing on object-oriented principles we assume that readers of this book have prior programming experiencealthough not necessarily using python this book does not provide complete description of the python language (there are numerous language references for that purpose)but it does introduce all aspects of the language that are used in code fragments later in this book the python interpreter python is formally an interpreted language commands are executed through piece of software known as the python interpreter the interpreter receives commandevaluates that commandand reports the result of the command while the interpreter can be used interactively (especially when debugging) programmer typically defines series of commands in advance and saves those commands in plain text file known as source code or script for pythonsource code is conventionally stored in file named with the py suffix ( demo pyon most operating systemsthe python interpreter can be started by typing python from the command line by defaultthe interpreter starts in interactive mode with clean workspace commands from predefined script saved in file ( demo pyare executed by invoking the interpreter with the filename as an argument ( python demo py)or using an additional - flag in order to execute script and then enter interactive mode ( python - demo pymany integrated development environments (idesprovide richer software development platforms for pythonincluding one named idle that is included with the standard python distribution idle provides an embedded text-editor with support for displaying and editing python codeand basic debuggerallowing step-by-step execution of program while examining key variable values
21,657
preview of python program as simple introductioncode fragment presents python program that computes the grade-point average (gpafor student based on letter grades that are entered by user many of the techniques demonstrated in this example will be discussed in the remainder of this at this pointwe draw attention to few high-level issuesfor readers who are new to python as programming language python' syntax relies heavily on the use of whitespace individual statements are typically concluded with newline characteralthough command can extend to another lineeither with concluding backslash character (\)or if an opening delimiter has not yet been closedsuch as the character in defining value map whitespace is also key in delimiting the bodies of control structures in python specificallya block of code is indented to designate it as the body of control structureand nested control structures use increasing amounts of indentation in code fragment the body of the while loop consists of the subsequent linesincluding nested conditional structure comments are annotations provided for human readersyet ignored by the python interpreter the primary syntax for comments in python is based on use of the characterwhich designates the remainder of the line as comment printwelcome to the gpa calculator printplease enter all your letter gradesone per line printenter blank line to designate the end map from letter grade to point value points : : : : : : : : : : : : num courses total points done false while not donegrade inputread line from user empty line was entered if grade =done true elif grade not in pointsunrecognized grade entered print("unknown grade { being ignoredformat(grade)elsenum courses + total points +points[gradeavoid division by zero if num courses printyour gpa is { format(total points num courses)code fragment python program that computes grade-point average (gpa
21,658
objects in python python is an object-oriented language and classes form the basis for all data types in this sectionwe describe key aspects of python' object modeland we introduce python' built-in classessuch as the int class for integersthe float class for floating-point valuesand the str class for character strings more thorough presentation of object-orientation is the focus of identifiersobjectsand the assignment statement the most important of all python commands is an assignment statementsuch as temperature this command establishes temperature as an identifier (also known as name)and then associates it with the object expressed on the right-hand side of the equal signin this case floating-point object with value we portray the outcome of this assignment in figure float temperature figure the identifier temperature references an instance of the float class having value identifiers identifiers in python are case-sensitiveso temperature and temperature are distinct names identifiers can be composed of almost any combination of lettersnumeralsand underscore characters (or more general unicode charactersthe primary restrictions are that an identifier cannot begin with numeral (thus lives is an illegal name)and that there are specially reserved words that cannot be used as identifiersas shown in table false none true and as assert break class continue def del elif reserved words else from in except global is finally if lambda for import nonlocal not or pass raise return try while with yield table listing of the reserved words in python these names cannot be used as identifiers
21,659
for readers familiar with other programming languagesthe semantics of python identifier is most similar to reference variable in java or pointer variable in +each identifier is implicitly associated with the memory address of the object to which it refers python identifier may be assigned to special object named noneserving similar purpose to null reference in java or +unlike java and ++python is dynamically typed languageas there is no advance declaration associating an identifier with particular data type an identifier can be associated with any type of objectand it can later be reassigned to another object of the same (or differenttype although an identifier has no declared typethe object to which it refers has definite type in our first examplethe characters are recognized as floating-point literaland thus the identifier temperature is associated with an instance of the float class having that value programmer can establish an alias by assigning second identifier to an existing object continuing with our earlier examplefigure portrays the result of subsequent assignmentoriginal temperature float temperature original figure identifiers temperature and original are aliases for the same object once an alias has been establishedeither name can be used to access the underlying object if that object supports behaviors that affect its statechanges enacted through one alias will be apparent when using the other alias (because they refer to the same objecthoweverif one of the names is reassigned to new value using subsequent assignment statementthat does not affect the aliased objectrather it breaks the alias continuing with our concrete examplewe consider the commandtemperature temperature the execution of this command begins with the evaluation of the expression on the right-hand side of the operator that expressiontemperature is evaluated based on the existing binding of the name temperatureand so the result has value that is that result is stored as new floating-point instanceand only then is the name on the left-hand side of the assignment statementtemperature(re)assigned to the result the subsequent configuration is diagrammed in figure of particular notethis last command had no effect on the value of the existing float instance that identifier original continues to reference float float temperature original figure the temperature identifier has been assigned to new valuewhile original continues to refer to the previously existing value
21,660
creating and using objects instantiation the process of creating new instance of class is known as instantiation in generalthe syntax for instantiating an object is to invoke the constructor of class for exampleif there were class named widgetwe could create an instance of that class using syntax such as widget)assuming that the constructor does not require any parameters if the constructor does require parameterswe might use syntax such as widget(abcto construct new instance many of python' built-in classes (discussed in section support what is known as literal form for designating new instances for examplethe command temperature results in the creation of new instance of the float classthe term in that expression is literal form we discuss further cases of python literals in the coming section from programmer' perspectiveyet another way to indirectly create new instance of class is to call function that creates and returns such an instance for examplepython has built-in function named sorted (see section that takes sequence of comparable elements as parameter and returns new instance of the list class containing those elements in sorted order calling methods python supports traditional functions (see section that are invoked with syntax such as sorted(data)in which case data is parameter sent to the function python' classes may also define one or more methods (also known as member functions)which are invoked on specific instance of class using the dot ("operator for examplepython' list class has method named sort that can be invoked with syntax such as data sortthis particular method rearranges the contents of the list so that they are sorted the expression to the left of the dot identifies the object upon which the method is invoked oftenthis will be an identifier ( data)but we can use the dot operator to invoke method upon the immediate result of some other operation for exampleif response identifies string instance (we will discuss strings later in this section)the syntax response lowerstartswithy first evaluates the method callresponse lower)which itself returns new string instanceand then the startswithy method is called on that intermediate string when using method of classit is important to understand its behavior some methods return information about the state of an objectbut do not change that state these are known as accessors other methodssuch as the sort method of the list classdo change the state of an object these methods are known as mutators or update methods
21,661
python' built-in classes table provides summary of commonly usedbuilt-in classes in pythonwe take particular note of which classes are mutable and which are immutable class is immutable if each object of that class has fixed value upon instantiation that cannot subsequently be changed for examplethe float class is immutable once an instance has been createdits value cannot be changed (although an identifier referencing that object can be reassigned to different valueclass bool int float list tuple str set frozenset dict description boolean value integer (arbitrary magnitudefloating-point number mutable sequence of objects immutable sequence of objects character string unordered set of distinct objects immutable form of set class associative mapping (aka dictionaryimmutable table commonly used built-in classes for python in this sectionwe provide an introduction to these classesdiscussing their purpose and presenting several means for creating instances of the classes literal forms (such as exist for most of the built-in classesand all of the classes support traditional constructor form that creates instances that are based upon one or more existing values operators supported by these classes are described in section more detailed information about these classes can be found in later as followslists and tuples ()strings and and appendix )sets and dictionaries (the bool class the bool class is used to manipulate logical (booleanvaluesand the only two instances of that class are expressed as the literals true and false the default constructorbool)returns falsebut there is no reason to use that syntax rather than the more direct literal form python allows the creation of boolean value from nonboolean type using the syntax bool(foofor value foo the interpretation depends upon the type of the parameter numbers evaluate to false if zeroand true if nonzero sequences and other container typessuch as strings and listsevaluate to false if empty and true if nonempty an important application of this interpretation is the use of nonboolean value as condition in control structure
21,662
the int class the int and float classes are the primary numeric types in python the int class is designed to represent integer values with arbitrary magnitude unlike java and ++which support different integral types with different precisions ( intshortlong)python automatically chooses the internal representation for an integer based upon the magnitude of its value typical literals for integers include and - in some contextsit is convenient to express an integral value using binaryoctalor hexadecimal that can be done by using prefix of the number and then character to describe the base example of such literals are respectively and the integer constructorint)returns value by default but this constructor can be used to construct an integer value based upon an existing value of another type for exampleif represents floating-point valuethe syntax int(fproduces the truncated value of for exampleboth int( and int( produce the value while int(- produces the value - the constructor can also be used to parse string that is presumed to represent an integral value (such as one entered by userif represents stringthen int(sproduces the integral value that string represents for examplethe expression int produces the integer value if an invalid string is given as parameteras in inthello ) valueerror is raised (see section for discussion of python' exceptionsby defaultthe string must use base if conversion from different base is desiredthat base can be indicated as secondoptionalparameter for examplethe expression int evaluates to the integer the float class the float class is the sole floating-point type in pythonusing fixed-precision representation its precision is more akin to double in java or ++rather than those languagesfloat type we have already discussed typical literal form we note that the floating-point equivalent of an integral number can be expressed directly as technicallythe trailing zero is optionalso some programmers might use the expression to designate this floating-point literal one other form of literal for floating-point values uses scientific notation for examplethe literal represents the mathematical value the constructor form of floatreturns when given parameterthe constructor attempts to return the equivalent floating-point value for examplethe call float( returns the floating-point value if the parameter to the constructor is stringas with float )it attempts to parse that string as floating-point valueraising valueerror as an exception
21,663
sequence typesthe listtupleand str classes the listtupleand str classes are sequence types in pythonrepresenting collection of values in which the order is significant the list class is the most generalrepresenting sequence of arbitrary objects (akin to an "arrayin other languagesthe tuple class is an immutable version of the list classbenefiting from streamlined internal representation the str class is specially designed for representing an immutable sequence of text characters we note that python does not have separate class for charactersthey are just strings with length one the list class list instance stores sequence of objects list is referential structureas it technically stores sequence of references to its elements (see figure elements of list may be arbitrary objects (including the none objectlists are array-based sequences and are zero-indexedthus list of length has elements indexed from to inclusive lists are perhaps the most used container type in python and they will be extremely central to our study of data structures and algorithms they have many valuable behaviorsincluding the ability to dynamically expand and contract their capacities as needed in this we will discuss only the most basic properties of lists we revisit the inner working of all of python' sequence types as the focus of python uses the characters as delimiters for list literalwith itself being an empty list as another examplered green blue is list containing three string instances the contents of list literal need not be expressed as literalsif identifiers and have been establishedthen syntax [abis legitimate the listconstructor produces an empty list by default howeverthe constructor will accept any parameter that is of an iterable type we will discuss iteration further in section but examples of iterable types include all of the standard container types ( stringslisttuplessetsdictionariesfor examplethe syntax listhello produces list of individual charactersh because an existing list is itself iterablethe syntax backup list(datacan be used to construct new list instance referencing the same contents as the original primes figure python' internal representation of list of integersinstantiated as prime [ the implicit indices of the elements are shown below each entry
21,664
the tuple class the tuple class provides an immutable version of sequenceand therefore its instances have an internal representation that may be more streamlined than that of list while python uses the characters to delimit listparentheses delimit tuplewith being an empty tuple there is one important subtlety to express tuple of length one as literala comma must be placed after the elementbut within the parentheses for example( ,is one-element tuple the reason for this requirement is thatwithout the trailing commathe expression ( is viewed as simple parenthesized numeric expression the str class python' str class is specifically designed to efficiently represent an immutable sequence of charactersbased upon the unicode international character set strings have more compact internal representation than the referential lists and tuplesas portrayed in figure figure python stringwhich is an indexed sequence of characters string literals can be enclosed in single quotesas in hello or double quotesas in "hellothis choice is convenientespecially when using another of the quotation characters as an actual character in the sequenceas in "don worryalternativelythe quote delimiter can be designated using backslash as so-called escape characteras in dont worry because the backslash has this purposethe backslash must itself be escaped to occur as natural character of the string literalas in :\\python\for string that would be displayed as :\pythonother commonly escaped characters are \ for newline and \ for tab unicode characters can be includedsuch as \ ac for the string or ""to begin and end string python also supports using the delimiter literal the advantage of such triple-quoted strings is that newline characters can be embedded naturally (rather than escaped as \nthis can greatly improve the readability of longmultiline strings in source code for exampleat the beginning of code fragment rather than use separate print statements for each line of introductory outputwe can use single print statementas followsprint("""welcome to the gpa calculator please enter all your letter gradesone per line enter blank line to designate the end """
21,665
the set and frozenset classes python' set class represents the mathematical notion of setnamely collection of elementswithout duplicatesand without an inherent order to those elements the major advantage of using setas opposed to listis that it has highly optimized method for checking whether specific element is contained in the set this is based on data structure known as hash table (which will be the primary topic of howeverthere are two important restrictions due to the algorithmic underpinnings the first is that the set does not maintain the elements in any particular order the second is that only instances of immutable types can be added to python set thereforeobjects such as integersfloating-point numbersand character strings are eligible to be elements of set it is possible to maintain set of tuplesbut not set of lists or set of setsas lists and sets are mutable the frozenset class is an immutable form of the set typeso it is legal to have set of frozensets python uses curly braces and as delimiters for setfor exampleas { or red green blue the exception to this rule is that does not represent an empty setfor historical reasonsit represents an empty dictionary (see next paragraphinsteadthe constructor syntax setproduces an empty set if an iterable parameter is sent to the constructorthen the set of distinct elements is produced for examplesethello produces the dict class python' dict class represents dictionaryor mappingfrom set of distinct keys to associated values for examplea dictionary might map from unique student id numbersto larger student records (such as the student' nameaddressand course gradespython implements dict using an almost identical approach to that of setbut with storage of the associated values dictionary literal also uses curly bracesand because dictionaries were introduced in python prior to setsthe literal form produces an empty dictionary nonempty dictionary is expressed using comma-separated series of key:value pairs for examplethe dictionary ga irish de german maps ga to irish and de to german the constructor for the dict class accepts an existing mapping as parameterin which case it creates new dictionary with identical associations as the existing one alternativelythe constructor accepts sequence of key-value pairs as parameteras in dict(pairswith pairs [ga irish )de german )
21,666
expressionsoperatorsand precedence in the previous sectionwe demonstrated how names can be used to identify existing objectsand how literals and constructors can be used to create instances of built-in classes existing values can be combined into larger syntactic expressions using variety of special symbols and keywords known as operators the semantics of an operator depends upon the type of its operands for examplewhen and are numbersthe syntax indicates additionwhile if and are stringsthe operator indicates concatenation in this sectionwe describe python' operators in various contexts of the built-in types we continuein section by discussing compound expressionssuch as cwhich rely on the evaluation of two or more operations the order in which the operations of compound expression are evaluated can affect the overall value of the expression for this reasonpython defines specific order of precedence for evaluating operatorsand it allows programmer to override this order by using explicit parentheses to group subexpressions logical operators python supports the following keyword operators for boolean valuesnot unary negation and conditional and or conditional or the and and or operators short-circuitin that they do not evaluate the second operand if the result can be determined based on the value of the first operand this feature is useful when constructing boolean expressions in which we first test that certain condition holds (such as reference not being none)and then test condition that could have otherwise generated an error condition had the prior test not succeeded equality operators python supports the following operators to test two notions of equalityis same identity is not different identity =equivalent !not equivalent the expression is evaluates to trueprecisely when identifiers and are aliases for the same object the expression = tests more general notion of equivalence if identifiers and refer to the same objectthen = should also evaluate to true yet = also evaluates to true when the identifiers refer to
21,667
different objects that happen to have values that are deemed equivalent the precise notion of equivalence depends on the data type for exampletwo strings are considered equivalent if they match character for character two sets are equivalent if they have the same contentsirrespective of order in most programming situationsthe equivalence tests =and !are the appropriate operatorsuse of is and is not should be reserved for situations in which it is necessary to detect true aliasing comparison operators data types may define natural order via the following operatorsless than <less than or equal to greater than >greater than or equal to these operators have expected behavior for numeric typesand are defined lexicographicallyand case-sensitivelyfor strings an exception is raised if operands have incomparable typesas with hello arithmetic operators python supports the following arithmetic operatorsaddition subtraction multiplication true division /integer division the modulo operator the use of additionsubtractionand multiplication is straightforwardnoting that if both operands have type intthen the result is an int as wellif one or both operands have type floatthe result will be float python takes more care in its treatment of division we first consider the case in which both operands have type intfor examplethe quantity divided by in mathematical notation in pythonthe operator designates true divisionreturning the floating-point result of the computation thus results in the float value python supports the pair of operators /and to perform the integral calculationswith expression / evaluating to int value (the mathematical floor of the quotient)and expression evaluating to int value the remainder of the integer division we note that languages such as cc++and java do not support the /operatorinsteadthe operator returns the truncated quotient when both operands have integral typeand the result of true division when at least one operand has floating-point type
21,668
python carefully extends the semantics of /and to cases where one or both operands are negative for the sake of notationlet us assume that variables and that and represent respectively the dividend and divisor of quotient / and python guarantees that will equal we already saw an example of this identity with positive operandsas when the divisor is positivepython further guarantees that < as consequencewe find that - / evaluates to - and - evaluates to as (- - when the divisor is negativepython guarantees that < as an example /- is - and - is - satisfying the identity (- (- (- the conventions for the /and operators are even extended to floatingpoint operandswith the expression / being the integral floor of the quotientand being the "remainderto ensure that equals for example / evaluates to and evaluates to as bitwise operators python provides the following bitwise operators for integersbitwise complement (prefix unary operatorbitwise and bitwise or bitwise exclusive-or <shift bits leftfilling in with zeros >shift bits rightfilling in with sign bit sequence operators each of python' built-in sequence types (strtupleand listsupport the following operator syntaxess[jelement at index [start:stopslice including indices [start,stops[start:stop:stepslice including indices startstart stepstart stepup to but not equalling or stop + concatenation of sequences shorthand for ( timesk val in containment check val not in non-containment check python relies on zero-indexing of sequencesthus sequence of length has elements indexed from to inclusive python also supports the use of negative indiceswhich denote distance from the end of the sequenceindex - denotes the last elementindex - the second to lastand so on python uses slicing
21,669
notation to describe subsequences of sequence slices are described as half-open intervalswith start index that is includedand stop index that is excluded for examplethe syntax data[ : denotes subsequence including the five indices an optional "stepvaluepossibly negativecan be indicated as third parameter of the slice if start index or stop index is omitted in the slicing notationit is presumed to designate the respective extreme of the original sequence because lists are mutablethe syntax [jval can be used to replace an element at given index lists also support syntaxdel [ ]that removes the designated element from the list slice notation can also be used to replace or delete sublist the notation val in can be used for any of the sequences to see if there is an element equivalent to val in the sequence for stringsthis syntax can be used to check for single character or for larger substringas with amp in example all sequences define comparison operations based on lexicographic orderperforming an element by element comparison until the first difference is found for example[ [ because of the entries at index thereforethe following operations are supported by sequence typess = equivalent (element by elements ! not equivalent lexicographically less than < lexicographically less than or equal to lexicographically greater than > lexicographically greater than or equal to operators for sets and dictionaries sets and frozensets support the following operatorskey in containment check key not in non-containment check = is equivalent to ! is not equivalent to < is subset of is proper subset of > is superset of is proper superset of the union of and the intersection of and the set of elements in but not the set of elements in precisely one of or note well that sets do not guarantee particular order of their elementsso the comparison operatorssuch as <are not lexicographicratherthey are based on the mathematical notion of subset as resultthe comparison operators define
21,670
partial orderbut not total orderas disjoint sets are neither "less than,"equal to,or "greater thaneach other sets also support many fundamental behaviors through named methods ( addremove)we will explore their functionality more fully in dictionarieslike setsdo not maintain well-defined order on their elements furthermorethe concept of subset is not typically meaningful for dictionariesso the dict class does not support operators such as dictionaries support the notion of equivalencewith = if the two dictionaries contain the same set of keyvalue pairs the most widely used behavior of dictionaries is accessing value associated with particular key with the indexing syntaxd[kthe supported operators are as followsd[keyd[keyvalue del [keykey in key not in = ! value associated with given key set (or resetthe value associated with given key remove key and its associated value from dictionary containment check non-containment check is equivalent to is not equivalent to dictionaries also support many useful behaviors through named methodswhich we explore more fully in extended assignment operators python supports an extended assignment operator for most binary operatorsfor exampleallowing syntax such as count + by defaultthis is shorthand for the more verbose count count for an immutable typesuch as number or stringone should not presume that this syntax changes the value of the existing objectbut instead that it will reassign the identifier to newly constructed value (see discussion of figure howeverit is possible for type to redefine such semantics to mutate the objectas the list class does for the +operator alpha [ beta alpha beta +[ beta beta [ print(alphaan alias for alpha extends the original list with two more elements reassigns beta to new list [ will be [ this example demonstrates the subtle difference between the list semantics for the syntax beta +foo versus beta beta foo
21,671
compound expressions and operator precedence programming languages must have clear rules for the order in which compound expressionssuch as are evaluated the formal order of precedence for operators in python is given in table operators in category with higher precedence will be evaluated before those with lower precedenceunless the expression is otherwise parenthesized thereforewe see that python gives precedence to multiplication over additionand therefore evaluates the expression as ( )with value but the parenthesized expression ( evaluates to value operators within category are typically evaluated from left to rightthus has value exceptions to this rule include that unary operators and exponentiation are evaluated from right to left python allows chained assignmentsuch as to assign multiple identifiers to the rightmost value python also allows the chaining of comparison operators for examplethe expression < < is evaluated as the compound ( < yand ( < )but without computing the intermediate value twice operator precedence type symbols member access expr member function/method calls exprcontainer subscripts/slices exprexponentiation unary operators +expr-expr~expr multiplicationdivision ///additionsubtraction +bitwise shifting bitwise-and bitwise-xor bitwise-or comparisons isis not==!=>containment innot in logical-not not expr logical-and and logical-or or conditional val if cond else val assignments =+=-==etc table operator precedence in pythonwith categories ordered from highest precedence to lowest precedence when statedwe use expr to denote literalidentifieror result of previously evaluated expression all operators without explicit mention of expr are binary operatorswith syntax expr operator expr
21,672
control flow in this sectionwe review python' most fundamental control structuresconditional statements and loops common to all control structures is the syntax used in python for defining blocks of code the colon character is used to delimit the beginning of block of code that acts as body for control structure if the body can be stated as single executable statementit can technically placed on the same lineto the right of the colon howevera body is more typically typeset as an indented block starting on the line following the colon python relies on the indentation level to designate the extent of that block of codeor any nested blocks of code within the same principles will be applied when designating the body of function (see section )and the body of class (see section conditionals conditional constructs (also known as if statementsprovide way to execute chosen block of code based on the run-time evaluation of one or more boolean expressions in pythonthe most general form of conditional is written as followsif first conditionfirst body elif second conditionsecond body elif third conditionthird body elsefourth body each condition is boolean expressionand each body contains one or more commands that are to be executed conditionally if the first condition succeedsthe first body will be executedno other conditions or bodies are evaluated in that case if the first condition failsthen the process continues in similar manner with the evaluation of the second condition the execution of this overall construct will cause precisely one of the bodies to be executed there may be any number of elif clauses (including zero)and the final else clause is optional as described on page nonboolean types may be evaluated as booleans with intuitive meanings for exampleif response is string that was entered by userand we want to condition behavior on this being nonempty stringwe may write if responseas shorthand for the equivalentif response !
21,673
as simple examplea robot controller might have the following logicif door is closedopen dooradvancenotice that the final commandadvance)is not indented and therefore not part of the conditional body it will be executed unconditionally (although after opening closed doorwe may nest one control structure within anotherrelying on indentation to make clear the extent of the various bodies revisiting our robot examplehere is more complex control that accounts for unlocking closed door if door is closedif door is lockedunlock dooropen dooradvancethe logic expressed by this example can be diagrammed as traditional flowchartas portrayed in figure false door is closed true false door is locked true unlock dooropen dooradvancefigure flowchart describing the logic of nested conditional statements
21,674
loops python offers two distinct looping constructs while loop allows general repetition based upon the repeated testing of boolean condition for loop provides convenient iteration of values from defined series (such as characters of stringelements of listor numbers within given rangewe discuss both forms in this section while loops the syntax for while loop in python is as followswhile conditionbody as with an if statementcondition can be an arbitrary boolean expressionand body can be an arbitrary block of code (including nested control structuresthe execution of while loop begins with test of the boolean condition if that condition evaluates to truethe body of the loop is performed after each execution of the bodythe loop condition is retestedand if it evaluates to trueanother iteration of the body is performed when the conditional test evaluates to false (assuming it ever does)the loop is exited and the flow of control continues just beyond the body of the loop as an examplehere is loop that advances an index through sequence of characters until finding an entry with value or reaching the end of the sequence = while len(dataand data[ ! + the len functionwhich we will introduce in section returns the length of sequence such as list or string the correctness of this loop relies on the shortcircuiting behavior of the and operatoras described on page we intentionally test len(datato ensure that is valid indexprior to accessing element data[jhad we written that compound condition with the opposite orderthe evaluation of data[jwould eventually raise an indexerror when is not found (see section for discussion of exceptions as writtenwhen this loop terminatesvariable ' value will be the index of the leftmost occurrence of if foundor otherwise the length of the sequence (which is recognizable as an invalid index to indicate failure of the searchit is worth noting that this code behaves correctlyeven in the special case when the list is emptyas the condition len(datawill initially fail and the body of the loop will never be executed
21,675
for loops python' for-loop syntax is more convenient alternative to while loop when iterating through series of elements the for-loop syntax can be used on any type of iterable structuresuch as listtuple strsetdictor file (we will discuss iterators more formally in section its general syntax appears as follows for element in iterablebody body may refer to element as an identifier for readers familiar with javathe semantics of python' for loop is similar to the "for eachloop style introduced in java as an instructive example of such loopwe consider the task of computing the sum of list of numbers (admittedlypython has built-in functionsumfor this purpose we perform the calculation with for loop as followsassuming that data identifies the listtotal for val in datatotal +val note use of the loop variableval the loop body executes once for each element of the data sequencewith the identifiervalfrom the for-loop syntax assigned at the beginning of each pass to respective element it is worth noting that val is treated as standard identifier if the element of the original data happens to be mutablethe val identifier can be used to invoke its methods but reassignment of identifier val to new value has no affect on the original datanor on the next iteration of the loop as second classic examplewe consider the task of finding the maximum value in list of elements (againadmitting that python' built-in max function already provides this supportif we can assume that the listdatahas at least one elementwe could implement this task as followsbiggest data[ for val in dataif val biggestbiggest val as we assume nonempty list although we could accomplish both of the above tasks with while loopthe for-loop syntax had an advantage of simplicityas there is no need to manage an explicit index into the list nor to author boolean loop condition furthermorewe can use for loop in cases for which while loop does not applysuch as when iterating through collectionsuch as setthat does not support any direct form of indexing
21,676
index-based for loops the simplicity of standard for loop over the elements of list is wonderfulhoweverone limitation of that form is that we do not know where an element resides within the sequence in some applicationswe need knowledge of the index of an element within the sequence for examplesuppose that we want to know where the maximum element in list resides rather than directly looping over the elements of the list in that casewe prefer to loop over all possible indices of the list for this purposepython provides built-in class named range that generates integer sequences (we will discuss generators in section in simplest formthe syntax range(ngenerates the series of values from to convenientlythese are precisely the series of valid indices into sequence of length thereforea standard python idiom for looping through the series of indices of data sequence uses syntaxfor in range(len(data))in this caseidentifier is not an element of the data--it is an integer but the expression data[jcan be used to retrieve the respective element for examplewe can find the index of the maximum element of list as followsbig index for in range(len(data))if data[jdata[big index]big index break and continue statements python supports break statement that immediately terminate while or for loop when executed within its body more formallyif applied within nested control structuresit causes the termination of the most immediately enclosing loop as typical examplehere is code that determines whether target value occurs in data setfound false for item in dataif item =targetfound true break python also supports continue statement that causes the current iteration of loop body to stopbut with subsequent passes of the loop proceeding as expected we recommend that the break and continue statements be used sparingly yetthere are situations in which these commands can be effectively used to avoid introducing overly complex logical conditions
21,677
functions in this sectionwe explore the creation of and use of functions in python as we did in section we draw distinction between functions and methods we use the general term function to describe traditionalstateless function that is invoked without the context of particular class or an instance of that classsuch as sorted(datawe use the more specific term method to describe member function that is invoked upon specific object using an object-oriented message passing syntaxsuch as data sortin this sectionwe only consider pure functionsmethods will be explored with more general object-oriented principles in we begin with an example to demonstrate the syntax for defining functions in python the following function counts the number of occurrences of given target value within any form of iterable data set def count(datatarget) = for item in dataif item =targetn + return found match the first linebeginning with the keyword defserves as the function' signature this establishes new identifier as the name of the function (countin this example)and it establishes the number of parameters that it expectsas well as names identifying those parameters (data and targetin this exampleunlike java and ++python is dynamically typed languageand therefore python signature does not designate the types of those parametersnor the type (if anyof return value those expectations should be stated in the function' documentation (see section and can be enforced within the body of the functionbut misuse of function will only be detected at run-time the remainder of the function definition is known as the body of the function as is the case with control structures in pythonthe body of function is typically expressed as an indented block of code each time function is calledpython creates dedicated activation record that stores information relevant to the current call this activation record includes what is known as namespace (see section to manage all identifiers that have local scope within the current call the namespace includes the function' parameters and any other identifiers that are defined locally within the body of the function an identifier in the local scope of the function caller has no relation to any identifier with the same name in the caller' scope (although identifiers in different scopes may be aliases to the same objectin our first examplethe identifier has scope that is local to the function callas does the identifier itemwhich is established as the loop variable
21,678
return statement return statement is used within the body of function to indicate that the function should immediately cease executionand that an expressed value should be returned to the caller if return statement is executed without an explicit argumentthe none value is automatically returned likewisenone will be returned if the flow of control ever reaches the end of function body without having executed return statement oftena return statement will be the final command within the body of the functionas was the case in our earlier example of count function howeverthere can be multiple return statements in the same functionwith conditional logic controlling which such command is executedif any as further exampleconsider the following function that tests if value exists in sequence def contains(datatarget)for item in targetif item =targetreturn true return false found match if the conditional within the loop body is ever satisfiedthe return true statement is executed and the function immediately endswith true designating that the target value was found converselyif the for loop reaches its conclusion without ever finding the matchthe final return false statement will be executed information passing to be successful programmerone must have clear understanding of the mechanism in which programming language passes information to and from function in the context of function signaturethe identifiers used to describe the expected parameters are known as formal parametersand the objects sent by the caller when invoking the function are the actual parameters parameter passing in python follows the semantics of the standard assignment statement when function is invokedeach identifier that serves as formal parameter is assignedin the function' local scopeto the respective actual parameter that is provided by the caller of the function for exampleconsider the following call to our count function from page prizes count(gradesa just before the function body is executedthe actual parametersgrades and are implicitly assigned to the formal parametersdata and targetas followsdata grades target
21,679
these assignment statements establish identifier data as an alias for grades and target as name for the string literal (see figure grades data target list str figure portrayal of parameter passing in pythonfor the function call count(gradesa identifiers data and target are formal parameters defined within the local scope of the count function the communication of return value from the function back to the caller is similarly implemented as an assignment thereforewith our sample invocation of prizes count(gradesa )the identifier prizes in the caller' scope is assigned to the object that is identified as in the return statement within our function body an advantage to python' mechanism for passing information to and from function is that objects are not copied this ensures that the invocation of function is efficienteven in case where parameter or return value is complex object mutable parameters python' parameter passing model has additional implications when parameter is mutable object because the formal parameter is an alias for the actual parameterthe body of the function may interact with the object in ways that change its state considering again our sample invocation of the count functionif the body of the function executes the command data appendf )the new entry is added to the end of the list identified as data within the functionwhich is one and the same as the list known to the caller as grades as an asidewe note that reassigning new value to formal parameter with function bodysuch as by setting data ]does not alter the actual parametersuch reassignment simply breaks the alias our hypothetical example of count method that appends new element to list lacks common sense there is no reason to expect such behaviorand it would be quite poor design to have such an unexpected effect on the parameter there arehowevermany legitimate cases in which function may be designed (and clearly documentedto modify the state of parameter as concrete examplewe present the following implementation of method named scale that' primary purpose is to multiply all entries of numeric data set by given factor def scale(datafactor)for in range(len(data))data[jfactor
21,680
default parameter values python provides means for functions to support more than one possible calling signature such function is said to be polymorphic (which is greek for "many forms"most notablyfunctions can declare one or more default values for parametersthereby allowing the caller to invoke function with varying numbers of actual parameters as an artificial exampleif function is declared with signature def foo(ab= = )there are three parametersthe last two of which offer default values caller is welcome to send three actual parametersas in foo( )in which case the default values are not used ifon the other handthe caller only sends one parameterfoo( )the function will execute with parameters values = = = if caller sends two parametersthey are assumed to be the first twowith the third being the default thusfoo( executes with = = = howeverit is illegal to define function with signature such as bar(ab= cwith having default valueyet not the subsequent cif default parameter value is present for one parameterit must be present for all further parameters as more motivating example for the use of default parameterwe revisit the task of computing student' gpa (see code fragment rather than assume direct input and output with the consolewe prefer to design function that computes and returns gpa our original implementation uses fixed mapping from each letter grade (such as -to corresponding point value (such as while that point system is somewhat commonit may not agree with the system used by all schools (for examplesome may assign an agrade value higher than thereforewe design compute gpa functiongiven in code fragment which allows the caller to specify custom mapping from grades to valueswhile offering the standard point system as default def compute gpa(gradespoints= : : : : : : : : : : : : })num courses total points for in gradesif in pointsa recognizable grade num courses + total points +points[greturn total points num courses code fragment function that computes student' gpa with point value system that can be customized as an optional parameter
21,681
as an additional example of an interesting polymorphic functionwe consider python' support for range (technicallythis is constructor for the range classbut for the sake of this discussionwe can treat it as pure function three calling syntaxes are supported the one-parameter formrange( )generates sequence of integers from up to but not including two-parameter formrange(start,stopgenerates integers from start up tobut not includingstop three-parameter formrange(startstopstep)generates similar range as range(startstop)but with increments of size step rather than this combination of forms seems to violate the rules for default parameters in particularwhen single parameter is sentas in range( )it serves as the stop value (which is the second parameter)the value of start is effectively in that case howeverthis effect can be achieved with some sleight of handas followsdef range(startstop=nonestep= )if stop is nonestop start start from technical perspectivewhen range(nis invokedthe actual parameter will be assigned to formal parameter start within the bodyif only one parameter is receivedthe start and stop values are reassigned to provide the desired semantics keyword parameters the traditional mechanism for matching the actual parameters sent by callerto the formal parameters declared by the function signature is based on the concept of positional arguments for examplewith signature foo( = = = )parameters sent by the caller are matchedin the given orderto the formal parameters an invocation of foo( indicates that = while and are assigned their default values python supports an alternate mechanism for sending parameter to function known as keyword argument keyword argument is specified by explicitly assigning an actual parameter to formal parameter by name for examplewith the above definition of function fooa call foo( = will invoke the function with parameters = = = function' author can require that certain parameters be sent only through the keyword-argument syntax we never place such restriction in our own function definitionsbut we will see several important uses of keyword-only parameters in python' standard libraries as an examplethe built-in max function accepts keyword parametercoincidentally named keythat can be used to vary the notion of "maximumthat is used
21,682
by defaultmax operates based upon the natural order of elements according to the operator for that type but the maximum can be computed by comparing some other aspect of the elements this is done by providing an auxiliary function that converts natural element to some other value for the sake of comparison for exampleif we are interested in finding numeric value with magnitude that is maximal ( considering - to be larger than + )we can use the calling syntax max(abkey=absin this casethe built-in abs function is itself sent as the value associated with the keyword parameter key (functions are first-class objects in pythonsee section when max is called in this wayit will compare abs(ato abs( )rather than to the motivation for the keyword syntax as an alternate to positional arguments is important in the case of max this function is polymorphic in the number of argumentsallowing call such as max( , , , )thereforeit is not possible to designate key function as traditional positional element sorting functions in python also support similar key parameter for indicating nonstandard order (we explore this further in section and in section when discussing sorting algorithmspython' built-in functions table provides an overview of common functions that are automatically available in pythonincluding the previously discussed absmaxand range when choosing names for the parameterswe use identifiers xyz for arbitrary numeric typesk for an integerand aband for arbitrary comparable types we use the identifieriterableto represent an instance of any iterable type ( strlisttuplesetdict)we will discuss iterators and iterable data types in section sequence represents more narrow category of indexable classesincluding strlistand tuplebut neither set nor dict most of the entries in table can be categorized according to their functionality as followsinput/outputprintinputand open will be more fully explained in section character encodingord and chr relate characters and their integer code points for exampleorda is and chr( is mathematicsabsdivmodpowroundand sum provide common mathematical functionalityan additional math module will be introduced in section orderingmax and min apply to any data type that supports notion of comparisonor to any collection of such values likewisesorted can be used to produce an ordered list of elements drawn from any existing collection collections/iterationsrange generates new sequence of numberslen reports the length of any existing collectionfunctions reversedallanyand map operate on arbitrary iterations as welliter and next provide general framework for iteration through elements of collectionand are discussed in section
21,683
calling syntax abs(xall(iterableany(iterablechr(integerdivmod(xyhash(objid(objinput(promptisinstance(objclsiter(iterablelen(iterablemap(fiter iter max(iterablemax(abcmin(iterablemin(abcnext(iteratoropen(filenamemodeord(charpow(xypow(xyzprint(obj obj range(stoprange(startstoprange(startstopstepreversed(sequenceround(xround(xksorted(iterablesum(iterabletype(objcommon built-in functions description return the absolute value of number return true if bool(eis true for each element return true if bool(eis true for at least one element return one-character string with the given unicode code point return ( /yx yas tupleif and are integers return an integer hash value for the object (see return the unique integer serving as an "identityfor the object return string from standard inputthe prompt is optional determine if obj is an instance of the class (or subclassreturn new iterator object for the parameter (see section return the number of elements in the given iteration return an iterator yielding the result of function calls ( for respective elements iter iter return the largest element of the given iteration return the largest of the arguments return the smallest element of the given iteration return the smallest of the arguments return the next element reported by the iterator (see section open file with the given name and access mode return the unicode code point of the given character return the value xy (as an integer if and are integers)equivalent to return the value (xy mod zas an integer print the argumentswith separating spaces and trailing newline construct an iteration of values stop construct an iteration of values startstart stop construct an iteration of values startstart stepstart stepreturn an iteration of the sequence in reverse return the nearest int value ( tie is broken toward the even valuereturn the value rounded to the nearest - (return-type matches xreturn list containing elements of the iterable in sorted order return the sum of the elements in the iterable (must be numericreturn the class to which the instance obj belongs table commonly used built-in function in python
21,684
simple input and output in this sectionwe address the basics of input and output in pythondescribing standard input and output through the user consoleand python' support for reading and writing text files console input and output the print function the built-in functionprintis used to generate standard output to the console in its simplest formit prints an arbitrary sequence of argumentsseparated by spacesand followed by trailing newline character for examplethe command printmaroon outputs the string maroon \ note that arguments need not be string instances nonstring argument will be displayed as str(xwithout any argumentsthe command printoutputs single newline character the print function can be customized through the use of the following keyword parameters (see section for discussion of keyword parameters)by defaultthe print function inserts separating space into the output between each pair of arguments the separator can be customized by providing desired separating string as keyword parametersep for examplecolonseparated output can be produced as print(abcsepthe separating string need not be single characterit can be longer stringand it can be the empty stringsepcausing successive arguments to be directly concatenated by defaulta trailing newline is output after the final argument an alternative trailing string can be designated using keyword parameterend designating the empty string endsuppresses all trailing characters by defaultthe print function sends its output to the standard console howeveroutput can be directed to file by indicating an output file stream (see section using file as keyword parameter the input function the primary means for acquiring information from the user console is built-in function named input this function displays promptif given as an optional parameterand then waits until the user enters some sequence of characters followed by the return key the formal return value of the function is the string of characters that were entered strictly before the return key ( no newline character exists in the returned string
21,685
when reading numeric value from the usera programmer must use the input function to get the string of charactersand then use the int or float syntax to construct the numeric value that character string represents that isif call to response inputreports that the user entered the characters the syntax int(responsecould be used to produce the integer value it is quite common to combine these operations with syntax such as year int(inputin what year were you born)if we assume that the user will enter an appropriate response (in section we discuss error handling in such situation because input returns string as its resultuse of that function can be combined with the existing functionality of the string classas described in appendix for exampleif the user enters multiple pieces of information on the same lineit is common to call the split method on the resultas in reply inputenter and yseparated by spacespieces reply splitreturns list of stringsas separated by spaces float(pieces[ ] float(pieces[ ] sample program here is simplebut completeprogram that demonstrates the use of the input and print functions the tools for formatting the final output is discussed in appendix age int(inputenter your age in years)max heart rate ( ageas per med sci sports exerc target max heart rate printyour target fat-burning heart rate is targetfiles files are typically accessed in python beginning with call to built-in functionnamed openthat returns proxy for interactions with the underlying file for examplethe commandfp opensample txt )attempts to open file named sample txtreturning proxy that allows read-only access to the text file the open function accepts an optional second parameter that determines the access mode the default mode is for reading other common modes are for writing to the file (causing any existing file with that name to be overwritten)or for appending to the end of an existing file although we focus on use of text filesit is possible to work with binary filesusing access modes such as rb or wb
21,686
when processing filethe proxy maintains current position within the file as an offset from the beginningmeasured in number of bytes when opening file with mode or the position is initially if opened in append modea the position is initially at the end of the file the syntax fp closecloses the file associated with proxy fpensuring that any written contents are saved summary of methods for reading and writing file is given in table calling syntax fp readfp read(kfp readlinefp readlinesfor line in fpfp seek(kfp tellfp write(stringfp writelines(seqprintfile=fpdescription return the (remainingcontents of readable file as string return the next bytes of readable file as string return (remainder of the current line of readable file as string return all (remaininglines of readable file as list of strings iterate all (remaininglines of readable file change the current position to be at the kth byte of the file return the current positionmeasured as byte-offset from the start write given string at current position of the writable file write each of the strings of the given sequence at the current position of the writable file this command does not insert any newlinesbeyond those that are embedded in the strings redirect output of print function to the file table behaviors for interacting with text file via file proxy (named fpreading from file the most basic command for reading via proxy is the read method when invoked on file proxy fpas fp read( )the command returns string representing the next bytes of the filestarting at the current position without parameterthe syntax fp readreturns the remaining contents of the file in entirety for conveniencefiles can be read line at timeusing the readline method to read one lineor the readlines method to return list of all remaining lines files also support the for-loop syntaxwith iteration being line by line ( for line in fp:writing to file when file proxy is writablefor exampleif created with access mode or text can be written using methods write or writelines for exampleif we define fp openresults txt )the syntax fp writehello world \ writes single line to the file with the given string note well that write does not explicitly add trailing newlineso desired newline characters must be embedded directly in the string parameter recall that the output of the print method can be redirected to file using keyword parameteras described in section
21,687
exception handling exceptions are unexpected events that occur during the execution of program an exception might result from logical error or an unanticipated situation in pythonexceptions (also known as errorsare objects that are raised (or thrownby code that encounters an unexpected circumstance the python interpreter can also raise an exception should it encounter an unexpected conditionlike running out of memory raised error may be caught by surrounding context that "handlesthe exception in an appropriate fashion if uncaughtan exception causes the interpreter to stop executing the program and to report an appropriate message to the console in this sectionwe examine the most common error types in pythonthe mechanism for catching and handling errors that have been raisedand the syntax for raising errors from within user-defined blocks of code common exception types python includes rich hierarchy of exception classes that designate various categories of errorstable shows many of those classes the exception class serves as base class for most other error types an instance of the various subclasses encodes details about problem that has occurred several of these errors may be raised in exceptional cases by behaviors introduced in this for exampleuse of an undefined identifier in an expression causes nameerrorand errant use of the dot notationas in foo bar)will generate an attributeerror if object foo does not support member named bar class exception attributeerror eoferror ioerror indexerror keyerror keyboardinterrupt nameerror stopiteration typeerror valueerror zerodivisionerror description base class for most error types raised by syntax obj fooif obj has no member named foo raised if "end of filereached for console or file input raised upon failure of / operation ( opening fileraised if index to sequence is out of bounds raised if nonexistent key requested for set or dictionary raised if user types ctrl- while program is executing raised if nonexistent identifier used raised by next(iteratorif no elementsee section raised when wrong type of parameter is sent to function raised when parameter has invalid value ( sqrt(- )raised when any division operator used with as divisor table common exception classes in python
21,688
sending the wrong numbertypeor value of parameters to function is another common cause for an exception for examplea call to abshello will raise typeerror because the parameter is not numericand call to abs( will raise typeerror because one parameter is expected valueerror is typically raised when the correct number and type of parameters are sentbut value is illegitimate for the context of the function for examplethe int constructor accepts stringas with int )but valueerror is raised if that string does not represent an integeras with int or inthello python' sequence types ( listtupleand strraise an indexerror when syntax such as data[kis used with an integer that is not valid index for the given sequence (as described in section sets and dictionaries raise keyerror when an attempt is made to access nonexistent element raising an exception an exception is thrown by executing the raise statementwith an appropriate instance of an exception class as an argument that designates the problem for exampleif function for computing square root is sent negative value as parameterit can raise an exception with the commandraise valueerrorx cannot be negative this syntax raises newly created instance of the valueerror classwith the error message serving as parameter to the constructor if this exception is not caught within the body of the functionthe execution of the function immediately ceases and the exception is propagated to the calling context (and possibly beyondwhen checking the validity of parameters sent to functionit is customary to first verify that parameter is of an appropriate typeand then to verify that it has an appropriate value for examplethe sqrt function in python' math library performs error-checking that might be implemented as followsdef sqrt( )if not isinstance( (intfloat))raise typeerrorx must be numeric elif raise valueerrorx cannot be negative do the real work here checking the type of an object can be performed at run-time using the built-in functionisinstance in simplest formisinstance(objclsreturns true if objectobjis an instance of classclsor any subclass of that type in the above examplea more general form is used with tuple of allowable types indicated with the second parameter after confirming that the parameter is numericthe function enforces an expectation that the number be nonnegativeraising valueerror otherwise
21,689
how much error-checking to perform within function is matter of debate checking the type and value of each parameter demands additional execution time andif taken to an extremeseems counter to the nature of python consider the built-in sum functionwhich computes sum of collection of numbers an implementation with rigorous error-checking might be written as followsdef sum(values)if not isinstance(valuescollections iterable)raise typeerrorparameter must be an iterable type total for in valuesif not isinstance( (intfloat))raise typeerrorelements must be numeric total totalv return total the abstract base classcollections iterableincludes all of python' iterable containers types that guarantee support for the for-loop syntax ( listtupleset)we discuss iterables in section and the use of modulessuch as collectionsin section within the body of the for loopeach element is verified as numeric before being added to the total far more direct and clear implementation of this function can be written as followsdef sum(values)total for in valuestotal total return total interestinglythis simple implementation performs exactly like python' built-in version of the function even without the explicit checksappropriate exceptions are raised naturally by the code in particularif values is not an iterable typethe attempt to use the for-loop syntax raises typeerror reporting that the object is not iterable in the case when user sends an iterable type that includes nonnumerical elementsuch as sum([ oops ]) typeerror is naturally raised by the evaluation of expression total the error message unsupported operand type(sfor +'floatand 'strshould be sufficiently informative to the caller perhaps slightly less obvious is the error that results from sum(alpha beta ]it will technically report failed attempt to add an int and strdue to the initial evaluation of total alpha when total has been initialized to in the remainder of this bookwe tend to favor the simpler implementations in the interest of clean presentationperforming minimal error-checking in most situations
21,690
catching an exception there are several philosophies regarding how to cope with possible exceptional cases when writing code for exampleif division / is to be computedthere is clear risk that zerodivisionerror will be raised when variable has value in an ideal situationthe logic of the program may dictate that has nonzero valuethereby removing the concern for error howeverfor more complex codeor in case where the value of depends on some external input to the programthere remains some possibility of an error one philosophy for managing exceptional cases is to "look before you leap the goal is to entirely avoid the possibility of an exception being raised through the use of proactive conditional test revisiting our division examplewe might avoid the offending situation by writingif ! ratio elsedo something else second philosophyoften embraced by python programmersis that "it is easier to ask for forgiveness than it is to get permission this quote is attributed to grace hopperan early pioneer in computer science the sentiment is that we need not spend extra execution time safeguarding against every possible exceptional caseas long as there is mechanism for coping with problem after it arises in pythonthis philosophy is implemented using try-except control structure revising our first examplethe division operation can be guarded as followstryratio except zerodivisionerrordo something else in this structurethe "tryblock is the primary code to be executed although it is single command in this exampleit can more generally be larger block of indented code following the try-block are one or more "exceptcaseseach with an identified error type and an indented block of code that should be executed if the designated error is raised within the try-block the relative advantage of using try-except structure is that the non-exceptional case runs efficientlywithout extraneous checks for the exceptional condition howeverhandling the exceptional case requires slightly more time when using tryexcept structure than with standard conditional statement for this reasonthe try-except clause is best used when there is reason to believe that the exceptional case is relatively unlikelyor when it is prohibitively expensive to proactively evaluate condition to avoid the exception
21,691
exception handling is particularly useful when working with user inputor when reading from or writing to filesbecause such interactions are inherently less predictable in section we suggest the syntaxfp opensample txt )for opening file with read access that command may raise an ioerror for variety of reasonssuch as non-existent fileor lack of sufficient privilege for opening file it is significantly easier to attempt the command and catch the resulting error than it is to accurately predict whether the command will succeed we continue by demonstrating few other forms of the try-except syntax exceptions are objects that can be examined when caught to do soan identifier must be established with syntax as followstryfp opensample txt except ioerror as eprintunable to open the fileein this casethe nameedenotes the instance of the exception that was thrownand printing it causes detailed error message to be displayed ( "file not found" try-statement may handle more than one type of exception for exampleconsider the following command from section age int(inputenter your age in years)this command could fail for variety of reasons the call to input will raise an eoferror if the console input fails if the call to input completes successfullythe int constructor raises valueerror if the user has not entered characters representing valid integer if we want to handle two or more types of errors in the same waywe can use single except-statementas in the following exampleage - an initially invalid choice while age < tryage int(inputenter your age in years)if age < printyour age must be positive except (valueerroreoferror)printinvalid response we use the tuple(valueerroreoferror)to designate the types of errors that we wish to catch with the except-clause in this implementationwe catch either errorprint responseand continue with another pass of the enclosing while loop we note that when an error is raised within the try-blockthe remainder of that body is immediately skipped in this exampleif the exception arises within the call to inputor the subsequent call to the int constructorthe assignment to age never occursnor the message about needing positive value because the value of age
21,692
will be unchangedthe while loop will continue if we preferred to have the while loop continue without printing the invalid response messagewe could have written the exception-clause as except (valueerroreoferror)pass the keywordpassis statement that does nothingyet it can serve syntactically as body of control structure in this waywe quietly catch the exceptionthereby allowing the surrounding while loop to continue in order to provide different responses to different types of errorswe may use two or more except-clauses as part of try-structure in our previous examplean eoferror suggests more insurmountable error than simply an errant value being entered in that casewe might wish to provide more specific error messageor perhaps to allow the exception to interrupt the loop and be propagated to higher context we could implement such behavior as followsage - an initially invalid choice while age < tryage int(inputenter your age in years)if age < printyour age must be positive except valueerrorprintthat is an invalid age specification except eoferrorprintthere was an unexpected error reading input raise let re-raise this exception in this implementationwe have separate except-clauses for the valueerror and eoferror cases the body of the clause for handling an eoferror relies on another technique in python it uses the raise statement without any subsequent argumentto re-raise the same exception that is currently being handled this allows us to provide our own response to the exceptionand then to interrupt the while loop and propagate the exception upward in closingwe note two additional features of try-except structures in python it is permissible to have final except-clause without any identified error typesusing syntax except:to catch any other exceptions that occurred howeverthis technique should be used sparinglyas it is difficult to suggest how to handle an error of an unknown type try-statement can have finally clausewith body of code that will always be executed in the standard or exceptional caseseven when an uncaught or re-raised exception occurs that block is typically used for critical cleanup worksuch as closing an open file
21,693
iterators and generators in section we introduced the for-loop syntax beginning asfor element in iterableand we noted that there are many types of objects in python that qualify as being iterable basic container typessuch as listtupleand setqualify as iterable types furthermorea string can produce an iteration of its charactersa dictionary can produce an iteration of its keysand file can produce an iteration of its lines userdefined types may also support iteration in pythonthe mechanism for iteration is based upon the following conventionsan iterator is an object that manages an iteration through series of values if variableiidentifies an iterator objectthen each call to the built-in functionnext( )produces subsequent element from the underlying serieswith stopiteration exception raised to indicate that there are no further elements an iterable is an objectobjthat produces an iterator via the syntax iter(objby these definitionsan instance of list is an iterablebut not itself an iterator with data [ ]it is not legal to call next(datahoweveran iterator object can be produced with syntaxi iter(data)and then each subsequent call to next(iwill return an element of that list the for-loop syntax in python simply automates this processcreating an iterator for the give iterableand then repeatedly calling for the next element until catching the stopiteration exception more generallyit is possible to create multiple iterators based upon the same iterable objectwith each iterator maintaining its own state of progress howeveriterators typically maintain their state with indirect reference back to the original collection of elements for examplecalling iter(dataon list instance produces an instance of the list iterator class that iterator does not store its own copy of the list of elements insteadit maintains current index into the original listrepresenting the next element to be reported thereforeif the contents of the original list are modified after the iterator is constructedbut before the iteration is completethe iterator will be reporting the updated contents of the list python also supports functions and classes that produce an implicit iterable series of valuesthat iswithout constructing data structure to store all of its values at once for examplethe call range( does not return list of numbersit returns range object that is iterable this object generates the million values one at timeand only as needed such lazy evaluation technique has great advantage in the case of rangeit allows loop of the formfor in range( ):to execute without setting aside memory for storing one million values alsoif such loop were to be interrupted in some fashionno time will have been spent computing unused values of the range
21,694
we see lazy evaluation used in many of python' libraries for examplethe dictionary class supports methods keys)values)and items)which respectively produce "viewof all keysvaluesor (key,valuepairs within dictionary none of these methods produces an explicit list of results insteadthe views that are produced are iterable objects based upon the actual contents of the dictionary an explicit list of values from such an iteration can be immediately constructed by calling the list class constructor with the iteration as parameter for examplethe syntax list(range( )produces list instance with values from to while the syntax list( values)produces list that has elements based upon the current values of dictionary we can similarly construct tuple or set instance based upon given iterable generators in section we will explain how to define class whose instances serve as iterators howeverthe most convenient technique for creating iterators in python is through the use of generators generator is implemented with syntax that is very similar to functionbut instead of returning valuesa yield statement is executed to indicate each element of the series as an exampleconsider the goal of determining all factors of positive integer for examplethe number has factors traditional function might produce and return list containing all factorsimplemented asdef factors( )results for in range( , + )if = results append(kreturn results traditional function that computes factors store factors in new list divides evenlythus is factor add to the list of factors return the entire list in contrastan implementation of generator for computing those factors could be implemented as followsdef factors( )for in range( , + )if = yield generator that computes factors divides evenlythus is factor yield this factor as next result notice use of the keyword yield rather than return to indicate result this indicates to python that we are defining generatorrather than traditional function it is illegal to combine yield and return statements in the same implementationother than zero-argument return statement to cause generator to end its execution if programmer writes loop such as for factor in factors( ):an instance of our generator is created for each iteration of the looppython executes our procedure
21,695
until yield statement indicates the next value at that pointthe procedure is temporarily interruptedonly to be resumed when another value is requested when the flow of control naturally reaches the end of our procedure (or zero-argument return statement) stopiteration exception is automatically raised although this particular example uses single yield statement in the source codea generator can rely on multiple yield statements in different constructswith the generated series determined by the natural flow of control for examplewe can greatly improve the efficiency of our generator for computing factors of numbernby only testing values up to the square root of that numberwhile reporting the factor // that is associated with each (unless // equals kwe might implement such generator as followsdef factors( ) = while nif = yield yield / + if =nyield generator that computes factors while sqrt(nspecial case if is perfect square we should note that this generator differs from our first version in that the factors are not generated in strictly increasing order for examplefactors( generates the series in closingwe wish to emphasize the benefits of lazy evaluation when using generator rather than traditional function the results are only computed if requestedand the entire series need not reside in memory at one time in facta generator can effectively produce an infinite series of values as an examplethe fibonacci numbers form classic mathematical sequencestarting with value then value and then each subsequent value being the sum of the two preceding values hencethe fibonacci series begins as the following generator produces this infinite series def fibonacci) = = while trueyield future = future keep going report valueaduring this pass this will be next value reported and subsequently this
21,696
additional python conveniences in this sectionwe introduce several features of python that are particularly convenient for writing cleanconcise code each of these syntaxes provide functionality that could otherwise be accomplished using functionality that we have introduced earlier in this howeverat timesthe new syntax is more clear and direct expression of the logic conditional expressions python supports conditional expression syntax that can replace simple control structure the general syntax is an expression of the formexpr if condition else expr this compound expression evaluates to expr if the condition is trueand otherwise evaluates to expr for those familiar with java or ++this is equivalent to the syntaxcondition expr expr in those languages as an exampleconsider the goal of sending the absolute value of variablento function (and without relying on the built-in abs functionfor the sake of exampleusing traditional control structurewe might accomplish this as followsif > param elseparam - result foo(paramcall the function with the conditional expression syntaxwe can directly assign value to variableparamas followsparam if > else - result foo(parampick the appropriate value call the function in factthere is no need to assign the compound expression to variable conditional expression can itself serve as parameter to the functionwritten as followsresult foo( if > else -nsometimesthe mere shortening of source code is advantageous because it avoids the distraction of more cumbersome control structure howeverwe recommend that conditional expression be used only when it improves the readability of the source codeand when the first of the two options is the more "naturalcasegiven its prominence in the syntax (we prefer to view the alternative value as more exceptional
21,697
comprehension syntax very common programming task is to produce one series of values based upon the processing of another series oftenthis task can be accomplished quite simply in python using what is known as comprehension syntax we begin by demonstrating list comprehensionas this was the first form to be supported by python its general form is as followsexpression for value in iterable if condition we note that both expression and condition may depend on valueand that the if-clause is optional the evaluation of the comprehension is logically equivalent to the following traditional control structure for computing resulting listresult for value in iterableif conditionresult append(expressionas concrete examplea list of the squares of the numbers from to nthat is [ ]can be created by traditional means as followssquares for in range( + )squares append( kwith list comprehensionthis logic is expressed as followssquares [ for in range( + )as second examplesection introduced the goal of producing list of factors for an integer that task is accomplished with the following list comprehensionfactors [ for in range( , + if = python supports similar comprehension syntaxes that respectively produce setgeneratoror dictionary we compare those syntaxes using our example for producing the squares of numbers for in range( + for in range( + for in range( + for in range( + list comprehension set comprehension generator comprehension dictionary comprehension the generator syntax is particularly attractive when results do not need to be stored in memory for exampleto compute the sum of the first squaresthe generator syntaxtotal sum( for in range( + ))is preferred to the use of an explicitly instantiated list comprehension as the parameter
21,698
packing and unpacking of sequences python provides two additional conveniences involving the treatment of tuples and other sequence types the first is rather cosmetic if series of comma-separated expressions are given in larger contextthey will be treated as single tupleeven if no enclosing parentheses are provided for examplethe assignment data results in identifierdatabeing assigned to the tuple ( this behavior is called automatic packing of tuple one common use of packing in python is when returning multiple values from function if the body of function executes the commandreturn xy it will be formally returning single object that is the tuple (xyas dual to the packing behaviorpython can automatically unpack sequenceallowing one to assign series of individual identifiers to the elements of sequence as an examplewe can write abcd range( which has the effect of assigning = = = and = as those are the four values in the sequence returned by the call to range for this syntaxthe right-hand side expression can be any iterable typeas long as the number of variables on the left-hand side is the same as the number of elements in the iteration this technique can be used to unpack tuples returned by function for examplethe built-in functiondivmod(ab)returns the pair of values ( /ba bassociated with an integer division although the caller can consider the return value to be single tupleit is possible to write quotientremainder divmod(abto separately identify the two entries of the returned tuple this syntax can also be used in the context of for loopwhen iterating over sequence of iterablesas in for xy in ( )( )( ]in this examplethere will be three iterations of the loop during the first passx= and = and so on this style of loop is quite commonly used to iterate through key-value pairs that are returned by the itemsmethod of the dict classas infor kv in mapping items)
21,699
simultaneous assignments the combination of automatic packing and unpacking forms technique known as simultaneous assignmentwhereby we explicitly assign series of values to series of identifiersusing syntaxxyz in effectthe right-hand side of this assignment is automatically packed into tupleand then automatically unpacked with its elements assigned to the three identifiers on the left-hand side when using simultaneous assignmentall of the expressions are evaluated on the right-hand side before any of the assignments are made to the left-hand variables this is significantas it provides convenient means for swapping the values associated with two variablesjk kj with this commandj will be assigned to the old value of kand will be assigned to the old value of without simultaneous assignmenta swap typically requires more delicate use of temporary variablesuch as temp = temp with the simultaneous assignmentthe unnamed tuple representing the packed values on the right-hand side implicitly serves as the temporary variable when performing such swap the use of simultaneous assignments can greatly simplify the presentation of code as an examplewe reconsider the generator on page that produces the fibonacci series the original code requires separate initialization of variables and to begin the series within each pass of the loopthe goal was to reassign and brespectivelyto the values of and + at the timewe accomplished this with brief use of third variable with simultaneous assignmentsthat generator can be implemented more directly as followsdef fibonacci)ab while trueyield ab ba+