id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
12,500 | my_list [ true my_list[ ]= ** my_list [ true my_name 'davidmy_name[ ]='xtraceback (most recent call last)file ""line in my_name[ ]='xtypeerror'strobject does not support item assignment note that the error (or tracebackmessage displayed above is obtained on mac os machine if you are running the above code snippet on windows machineyour error output will more likely be as follows my_name[ ]='xtraceback (most recent call last)file ""line in -toplevelmy_name[ ]='xtypeerrorobject doesn' support item assignment depending on your operating systemor version of pythonthe output may slightly vary however it will still indicate where and what the error is you may want to experiment for yourself and get acquainted with the error message for easier and faster debugging for the remainder of this workwe will only display the mac os error messages tuples are very similar to lists in that they are heterogeneous sequences of data the difference is that tuple is immutablelike string tuple cannot be changed tuples are written as comma-delimited values enclosed in parentheses as sequencesthey can use any operation described above for examplemy_tuple ( ,true, my_tuple ( true len(my_tuple my_tuple[ my_tuple ( true true true my_tuple[ : ( truehoweverif you try to change an item in tupleyou will get an error note that the error message provides location and reason for the problem review of basic python |
12,501 | operator in len <use in(setlen(setset set set set set set set <set explanation set membership returns the cardinality ( the lengthof the set returns new set with all elements from both sets returns new set with only the elements common to both sets returns new set with all items from the first set not in second asks whether all elements of the first set are in the second table operations on set in python my_tuple[ ]=false traceback (most recent call last)file ""line in my_tuple[ ]=false typeerror'tupleobject does not support item assignment set is an unordered collection of zero or more immutable python data objects sets do not allow duplicates and are written as comma-delimited values enclosed in curly braces the empty set is represented by set(sets are heterogeneousand the collection can be assigned to variable as below { , ,"cat", ,false{false 'cat'my_set { , ,"cat", ,falsemy_set {false 'cat'even though sets are not considered to be sequentialthey do support few of the familiar operations presented earlier table reviews these operations and the following session gives examples of their use my_set {false 'cat'len(my_set false in my_set true "dogin my_set false sets support number of methods that should be familiar to those who have worked with them in mathematics setting table provides summary examples of their use follow note that unionintersectionissubsetand difference all have operators that can be used as well introduction |
12,502 | method name use union set union(set explanation returns new set with all elements from both sets intersection set intersection(set returns new set with only the elements common to both sets difference set difference(set returns new set with all items from first set not in second issubset set issubset(set asks whether all elements of one set are in the other add set add(itemadds item to the set remove set remove(itemremoves item from the set pop set pop(removes an arbitrary element from the set clear set clear(removes all elements from the set table methods provided by sets in python my_set {false 'cat'your_set { , , my_set union(your_set{false 'cat' my_set your_set {false 'cat' my_set intersection(your_set{ my_set your_set { my_set difference(your_set{false 'cat'my_set your_set {false 'cat'{ , issubset(your_settrue { , <your_set true my_set add("house"my_set {false 'house''cat'my_set remove( my_set {false 'house''cat'my_set pop(false my_set { 'house''cat'my_set clear(my_set set( review of basic python |
12,503 | operator [in del use explanation my_dict[kreturns the value associated with kotherwise its an error key in my_dict returns true if key is in the dictionaryfalse otherwise del my_dict[keyremoves the entry from the dictionary table operators provided by dictionaries in python our final python collection is an unordered structure called dictionary dictionaries are collections of associated pairs of items where each pair consists of key and value this key-value pair is typically written as key:value dictionaries are written as comma-delimited key:value pairs enclosed in curly braces for examplecapitals {'iowa':'desmoines','wisconsin':'madison'capitals {'wisconsin''madison''iowa''desmoines'we can manipulate dictionary by accessing value via its key or by adding another key-value pair the syntax for access looks much like sequence access except that instead of using the index of the item we use the key value to add new value is similar capitals {'iowa':'desmoines','wisconsin':'madison'print(capitals['iowa']capitals['utah']='saltlakecityprint(capitalscapitals['california']='sacramentoprint(len(capitals)for in capitalsprint(capitals[ ],is the capital of "kit is important to note that the dictionary is maintained in no particular order with respect to the keys the first pair added ('utah''saltlakecity'was placed first in the dictionary and the second pair added ('california''sacramento'was placed last the placement of key is dependent on the idea of "hashing,which will be explained in more detail in we also show the length function performing the same role as with previous collections dictionaries have both methods and operators table and table describe themand the session shows them in action the keysvaluesand items methods all return objects that contain the values of interest you can use the list function to convert them to lists you will also see that there are two variations on the get method if the key is not present in the dictionaryget will return none howevera secondoptional parameter can specify return value instead phone_ext={'david': 'brad': phone_ext {'brad' 'david' phone_ext keys(returns the keys of the dictionary phone_ext introduction |
12,504 | method name keys values items get get use explanation returns the keys of the dictionary in dict_keys object my_dict values(returns the values of the dictionary in dict_values object my_dict items(returns the key-value pairs in dict_items object my_dict get(kreturns the value associated with knone otherwise my_dict get( ,altreturns the value associated with kalt otherwise my_dict keys(table methods provided by dictionaries in python dict_keys(['brad''david']list(phone_ext keys()['brad''david'"bradin phone_ext true in phone_ext false is not key in phone_ext phone_ext values(returns the values of the dictionary phone_ext dict_values([ ]list(phone_ext values()[ phone_ext items(dict_items([('brad' )('david' )]list(phone_ext items()[('brad' )('david' )phone_ext get("kent"phone_ext get("kent","no entry"'no entrydel phone_ext["david"phone_ext {'brad' input and output we often have need to interact with userseither to get data or to provide some sort of result most programs today use dialog box as way of asking the user to provide some type of input while python does have way to create dialog boxesthere is much simpler function that we can use python provides us with function that allows us to ask user to enter some data and returns reference to the data in the form of string the function is called input python' input function takes single parameter that is string this string is often called the prompt because it contains some helpful text prompting the user to enter something for exampleyou might call input as follows review of basic python |
12,505 | user_name input('please enter your name'now whatever the user types after the prompt will be stored in the user_name variable using the input functionwe can easily write instructions that will prompt the user to enter data and then incorporate that data into further processing for examplein the following two statementsthe first asks the user for their name and the second prints the result of some simple processing based on the string that is provided user_name input("please enter your name "print("your name in all capitals is",user_name upper()"and has length"len(user_name)it is important to note that the value returned from the input function will be string representing the exact characters that were entered after the prompt if you want this string interpreted as another typeyou must provide the type conversion explicitly in the statements belowthe string that is entered by the user is converted to float so that it can be used in further arithmetic processing user_radius input("please enter the radius of the circle "radius float(user_radiusdiameter radius string formatting we have already seen that the print function provides very simple way to output values from python program print takes zero or more parameters and displays them using single blank as the default separator it is possible to change the separator character by setting the sep argument in additioneach print ends with newline character by default this behavior can be changed by setting the end argument these variations are shown in the following sessionprint("hello"hello print("hello","world"hello world print("hello","world"sep="***"hello***world print("hello","world"end="***"hello world**print("hello"end="***")print("world"hello***world it is often useful to have more control over the look of your output fortunatelypython provides us with an alternative called formatted strings formatted string is template in introduction |
12,506 | character output format , integer unsigned integer floating point as ddddd floating point as ddddde+/-xx floating point as ddddde+/-xx use % for exponents less than - or greater than + otherwise us % single character stringor any python data object that can be converted to string by using the str function insert literal character table string formatting conversion characters which words or spaces that will remain constant are combined with placeholders for variables that will be inserted into the string for examplethe statement print(name"is"age"years old "contains the words is and years oldbut the name and the age will change depending on the variable values at the time of execution using formatted stringwe write the previous statement as print("% is % years old (nameage)this simple example illustrates new string expression the operator is string operator called the format operator the left side of the expression holds the template or format stringand the right side holds collection of values that will be substituted into the format string note that the number of values in the collection on the right side corresponds with the number of characters in the format string values are taken in orderleft to right from the collection and inserted into the format string let' look at both sides of this formatting expression in more detail the format string may contain one or more conversion specifications conversion character tells the format operator what type of value is going to be inserted into that position in the string in the example abovethe % specifies stringwhile the % specifies an integer other possible type specifications include iufegcor table summarizes all of the various type specifications in addition to the format characteryou can also include format modifier between the and the format character format modifiers may be used to left-justify or right-justify the value with specified field width modifiers can also be used to specify the field width along with number of digits after the decimal point table explains these format modifiers the right side of the format operator is collection of values that will be inserted into the format string the collection will be either tuple or dictionary if the collection is tuplethe values are inserted in order of position that isthe first element in the tuple corresponds to the first format character in the format string if the collection is dictionarythe values are inserted according to their keys in this case all format characters must use the (name review of basic python |
12,507 | modifier example number % %- %+ % % (name%(name) description put the value in field width of put the value in field characters wideleft-justified put the value in field characters wideright-justified put the value in field characters widefill in with leading zeros put the value in field characters wide with characters to the right of the decimal point get the value from the supplied dictionary using name as the key table additional formatting options modifier to specify the name of the key price item "bananaprint("the % costs % cents"%(item,price)the banana costs cents print("the %+ costs % cents"%(item,price)the banana costs cents print("the %+ costs % cents"%(item,price)the banana costs cents item_dict {"item":"banana","cost": print("the %(item) costs %(cost) cents"%item_dictthe banana costs cents in addition to format strings that use format characters and format modifierspython strings also include format method that can be used in conjunction with new formatter class to implement complex string formatting more about these features can be found in the python library reference manual control structures as we noted earlieralgorithms require two important control structuresiteration and selection both of these are supported by python in various forms the programmer can choose the statement that is most useful for the given circumstance for iterationpython provides standard while statement and very powerful for statement the while statement repeats body of code as long as condition is true for examplecounter while counter < print("helloworld"counter counter helloworld helloworld introduction |
12,508 | helloworld helloworld helloworld prints out the phrase "helloworldfive times the condition on the while statement is evaluated at the start of each repetition if the condition is truethe body of the statement will execute it is easy to see the structure of python while statement due to the mandatory indentation pattern that the language enforces the while statement is very general purpose iterative structure that we will use in number of different algorithms in many casesa compound condition will control the iteration fragment such as while counter < and not donewould cause the body of the statement to be executed only in the case where both parts of the condition are satisfied the value of the variable counter would need to be less than or equal to and the value of the variable done would need to be false (not false is trueso that true and true results in true even though this type of construct is very useful in wide variety of situationsanother iterative structurethe for statementcan be used in conjunction with many of the python collections the for statement can be used to iterate over the members of collectionso long as the collection is sequence sofor examplefor item in [ , , , , ]print(item assigns the variable item to be each successive value in the list [ the body of the iteration is then executed this works for any collection that is sequence (liststuplesand stringsa common use of the for statement is to implement definite iteration over range of values the statement for item in range( )print(item * review of basic python |
12,509 | will perform the print function five times the range function will return range object representing the sequence and each value will be assigned to the variable item this value is then squared and printed the other very useful version of this iteration structure is used to process each character of string the following code fragment iterates over list of strings and for each string processes each character by appending it to list the result is list of all the letters in all of the words word_list ['cat','dog','rabbit'letter_list for a_word in word_listfor a_letter in a_wordletter_list append(a_letterprint(letter_listselection statements allow programmers to ask questions and thenbased on the resultperform different actions most programming languages provide two versions of this useful constructthe ifelse and the if simple example of binary selection uses the ifelse statement if print("sorryvalue is negative"elseprint(math sqrt( )in this examplethe object referred to by is checked to see if it is less than zero if it isa message is printed stating that it is negative if it is notthe statement performs the else clause and computes the square root selection constructsas with any control constructcan be nested so that the result of one question helps decide whether to ask the next for exampleassume that score is variable holding reference to score for computer science test if score > print(' 'elseif score > print(' 'elseif score > print(' 'elseif score > print(' 'else introduction |
12,510 | print(' 'python also has single way selection constructthe if statement with this statementif the condition is truean action is performed in the case where the condition is falseprocessing simply continues on to the next statement after the if for examplethe following fragment will first check to see if the value of variable is negative if it isthen it is modified by the absolute value function regardlessthe next action is to compute the square root if abs(nprint(math sqrt( )returning to liststhere is an alternative method for creating list that uses iteration and selection constructs the is known as list comprehension list comprehension allows you to easily create list based on some processing or selection criteria for exampleif we would like to create list of the first perfect squareswe could use for statementsq_list [for in range( )sq_list append( xsq_list [ using list comprehensionwe can do this in one step as sq_list [ for in range( )sq_list [ the variable takes on the values through as specified by the for construct the value of is then computed and added to the list that is being constructed the general syntax for list comprehension also allows selection criteria to be added so that only certain items get added for examplesq_list [ for in range( if ! sq_list [ this list comprehension constructed list that only contained the squares of the odd numbers in the range from to any sequence that supports iteration can be used within list comprehension to construct new list [ch upper(for ch in 'comprehensionif ch not in 'aeiou' review of basic python |
12,511 | [' '' '' '' '' '' '' '' 'self check test your understanding of what we have covered so far by trying the following two exercises use the code belowseen earlier in this subsection word_list ['cat','dog','rabbit'letter_list for a_word in word_listfor a_letter in a_wordletter_list append(a_letterprint(letter_list modify the given code so that the final list only contains single copy of each letter the answer is[' '' '' '' '' '' '' '' '' ' redo the given code using list comprehensions for an extra challengesee if you can figure out how to remove the duplicates the answer is[' '' '' '' '' '' '' '' '' '' '' '' 'exception handling there are two types of errors that typically occur when writing programs the firstknown as syntax errorsimply means that the programmer has made mistake in the structure of statement or expression for exampleit is incorrect to write for statement and forget the colon for in range( syntaxerrorinvalid syntax in this casethe python interpreter has found that it cannot complete the processing of this instruction since it does not conform to the rules of the language syntax errors are usually more frequent when you are first learning language the other type of errorknown as logic errordenotes situation where the program executes but gives the wrong result this can be due to an error in the underlying algorithm or an error in your translation of that algorithm in some caseslogic errors lead to very bad situations such as trying to divide by zero or trying to access an item in list where the index of the item is outside the bounds of the list in this casethe logic error leads to runtime error that causes the program to terminate these types of runtime errors are typically called exceptions introduction |
12,512 | most of the timebeginning programmers simply think of exceptions as fatal runtime errors that cause the end of execution howevermost programming languages provide way to deal with these errors that will allow the programmer to have some type of intervention if they so choose in additionprogrammers can create their own exceptions if they detect situation in the program execution that warrants it when an exception occurswe say that it has been "raised you can "handlethe exception that has been raised by using try statement for exampleconsider the following session that asks the user for an integer and then calls the square root function from the math library if the user enters value that is greater than or equal to the print will show the square root howeverif the user enters negative valuethe square root function will report valueerror exception a_number int(input("please enter an integer ")please enter an integer - print(math sqrt(a_number)traceback (most recent call last)file ""line in print(math sqrt(a_number)valueerrormath domain error we can handle this exception by calling the print function from within try block corresponding except block "catchesthe exception and prints message back to the user in the event that an exception occurs for exampletryprint(math sqrt(a_number)exceptprint("bad value for square root"print("using absolute value instead"print(math sqrt(abs(a_number))bad value for square root using absolute value instead will catch the fact that an exception is raised by sqrt and will instead print the messages back to the user and use the absolute value to be sure that we are taking the square root of nonnegative number this means that the program will not terminate but instead will continue on to the next statements it is also possible for programmer to cause runtime exception by using the raise statement for exampleinstead of calling the square root function with negative numberwe could have checked the value first and then raised our own exception the code fragment below shows the result of creating new runtimeerror exception note that the program would still terminate but now the exception that caused the termination is something explicitly created by review of basic python |
12,513 | the programmer if a_number raise runtimeerror("you can' use negative number"elseprint(math sqrt(a_number)traceback (most recent call last)file ""line in raise runtimeerror("you can' use negative number"runtimeerroryou can' use negative number there are many kinds of exceptions that can be raised in addition to the runtimeerror shown above see the python reference manual for list of all the available exception types and for how to create your own defining functions the earlier example of procedural abstraction called upon python function called sqrt from the math module to compute the square root in generalwe can hide the details of any computation by defining function function definition requires namea group of parametersand body it may also explicitly return value for examplethe simple function defined below returns the square of the value you pass into it def square( )return * square( square(square( ) the syntax for this function definition includes the namesquareand parenthesized list of formal parameters for this functionn is the only formal parameterwhich suggests that square needs only one piece of data to do its work the detailshidden "inside the box,simply compute the result of * and return it we can invoke or call the square function by asking the python environment to evaluate itpassing an actual parameter valuein this case note that the call to square returns an integer that can in turn be passed to another invocation we could implement our own square root function by using well-known technique called "newton' method newton' method for approximating square roots performs an iterative computation that converges on the correct value the equation new_guess old_guess * old_guess introduction |
12,514 | takes value and repeatedly guesses the square root by making each new_guess the old_guess in the subsequent iteration the initial guess used here is listing shows function definition that accepts value and returns the square root of after making guesses againthe details of newton' method are hidden inside the function definition and the user does not have to know anything about the implementation to use the function for its intended purpose listing also shows the use of the character as comment marker any characters that follow the on line are ignored listing square_root function def square_root( )root #initial guess will be / of for in range( )root ( (root ( root)return root square_root( square_root( self check here is self check that really covers everything so far you may have heard of the infinite monkey theoremthe theorem states that monkey hitting keys at random on typewriter keyboard for an infinite amount of time will almost surely type given textsuch as the complete works of william shakespeare wellsuppose we replace monkey with python function how long do you think it would take for python function to generate just one sentence of shakespearethe sentence we'll shoot for is"methinks it is like weaselyou are not going to want to run this one in the browserso fire up your favorite python ide the way we will simulate this is to write function that generates string that is characters long by choosing random letters from the letters in the alphabet plus the space we will write another function that will score each generated string by comparing the randomly generated string to the goal third function will repeatedly call generate and scorethen if of the letters are correct we are done if the letters are not correct then we will generate whole new string to make it easier to follow your program' progress this third function should print out the best string generated so far and its score every tries self check challenge see if you can improve upon the program in the self check by keeping letters that are correct and only modifying one character in the best string so far this is type of algorithm in the review of basic python |
12,515 | class of "hill climbingalgorithmsthat is we only keep the result if it is better than the previous one object-oriented programming in pythondefining classes we stated earlier that python is an object-oriented programming language so farwe have used number of built-in classes to show examples of data and control structures one of the most powerful features in an object-oriented programming language is the ability to allow programmer (problem solverto create new classes that model data that is needed to solve the problem remember that we use abstract data types to provide the logical description of what data object looks like (its stateand what it can do (its methodsby building class that implements an abstract data typea programmer can take advantage of the abstraction process and at the same time provide the details necessary to actually use the abstraction in program whenever we want to implement an abstract data typewe will do so with new class fraction class very common example to show the details of implementing user-defined class is to construct class to implement the abstract data type fraction we have already seen that python provides number of numeric classes for our use there are timeshoweverthat it would be most appropriate to be able to create data objects that "look likefractions fraction such as consists of two parts the top valueknown as the numeratorcan be any integer the bottom valuecalled the denominatorcan be any integer greater than (negative fractions have negative numeratoralthough it is possible to create floating point approximation for any fractionin this case we would like to represent the fraction as an exact value the operations for the fraction type will allow fraction data object to behave like any other numeric value we need to be able to addsubtractmultiplyand divide fractions we also want to be able to show fractions using the standard "slashformfor example in additionall fraction methods should return results in their lowest terms so that no matter what computation is performedwe always end up with the most common form in pythonwe define new class by providing name and set of method definitions that are syntactically similar to function definitions for this exampleclass fraction#the methods go here provides the framework for us to define the methods the first method that all classes should provide is the constructor the constructor defines the way in which data objects are created to create fraction objectwe will need to provide two pieces of datathe numerator and the denominator in pythonthe constructor method is always called __init__(two introduction |
12,516 | figure an instance of the fraction class underscores before and after initand is shown in listing listing fraction class and its constructor class fractiondef __init__(self,top,bottom)self num top self den bottom notice that the formal parameter list contains three items (selftopbottomself is special parameter that will always be used as reference back to the object itself it must always be the first formal parameterhoweverit will never be given an actual parameter value upon invocation as described earlierfractions require two pieces of state datathe numerator and the denominator the notation self num in the constructor defines the fraction object to have an internal data object called num as part of its state likewiseself den creates the denominator the values of the two formal parameters are initially assigned to the stateallowing the new fraction object to know its starting value to create an instance of the fraction classwe must invoke the constructor this happens by using the name of the class and passing actual values for the necessary state (note that we never directly invoke __init__for examplemy_fraction fraction( , creates an object called my_fraction representing the fraction (three-fifthsfigure shows this object as it is now implemented the next thing we need to do is implement the behavior that the abstract data type requires to beginconsider what happens when we try to print fraction object my_f fraction( print(my_f review of basic python |
12,517 | the fraction objectmy_fdoes not know how to respond to this request to print the print function requires that the object convert itself into string so that the string can be written to the output the only choice my_f has is to show the actual reference that is stored in the variable (the address itselfthis is not what we want there are two ways we can solve this problem one is to define method called show that will allow the fraction object to print itself as string we can implement this method as shown in listing if we create fraction object as beforewe can ask it to show itselfin other wordsprint itself in the proper format unfortunatelythis does not work in general in order to make printing work properlywe need to tell the fraction class how to convert itself into string this is what the print function needs in order to do its job listing show function def show(self)print(self num"/"self denmy_f fraction( my_f show( print(my_fin pythonall classes have set of standard methods that are provided but may not work properly one of these__str__is the method to convert an object into string the default implementation for this method is to return the instance address string as we have already seen what we need to do is provide "betterimplementation for this method we will say that this implementation overrides the previous oneor that it redefines the method' behavior to do thiswe simply define method with the name __str__ and give it new implementation as shown in listing this definition does not need any other information except the special parameter self in turnthe method will build string representation by converting each piece of internal state data to string and then placing character in between the strings using string concatenation the resulting string will be returned any time fraction object is asked to convert itself to string notice the various ways that this function is used listing standard method def __str__ (self)return str(self num"/str(self denmy_f fraction( print(my_f / print(" ate"my_f"of the pizza" ate / of the pizza my_f __str__( introduction |
12,518 | ' / str(my_f' / we can override many other methods for our new fraction class some of the most important of these are the basic arithmetic operations we would like to be able to create two fraction objects and then add them together using the standard "+notation at this pointif we try to add two fractionswe get the followingf fraction( , fraction( , traceback (most recent call last)file ""line in typeerrorunsupported operand type(sfor +'fractionand 'fractionif you look closely at the erroryou see that the problem is that the "+operator does not understand the fraction operands we can fix this by providing the fraction class with method that overrides the addition method in pythonthis method is called __add__ and it requires two parameters the firstselfis always neededand the second represents the other operand in the expression for examplef __add__( would ask the fraction object to add the fraction object to itself this can be written in the standard notationf two fractions must have the same denominator to be added the easiest way to make sure they have the same denominator is to simply use the product of the two denominators as common denominator so that ad cb ad cb bd bd bd the implementation is shown in listing the addition function returns new fraction object with the numerator and denominator of the sum we can use this method by writing standard arithmetic expression involving fractionsassigning the result of the additionand then printing our result listing adding fractions def __add__(selfother_fraction)new_num self num*other_fraction den self den*other_fraction num new_den self den other_fraction den review of basic python |
12,519 | return fraction(new_numnew_denf fraction( fraction( print( / the addition method works as we desirebut one thing could be better note that is the correct result but that it is not in the "lowest termsrepresentation the best representation would be in order to be sure that our results are always in the lowest termswe need helper function that knows how to reduce fractions this function will need to look for the greatest common divisoror gcd we can then divide the numerator and the denominator by the gcd and the result will be reduced to lowest terms the best-known algorithm for finding greatest common divisor is euclid' algorithm euclid' algorithm states that the greatest common divisor of two integers and is if divides evenly howeverif does not divide evenlythen the answer is the greatest common divisor of and the remainder of divided by we will simply provide an iterative implementation here note that this implementation of the gcd algorithm only works when the denominator is positive this is acceptable for our fraction class because we have said that negative fraction will be represented by negative numerator def gcd(mn)while ! old_m old_n old_n old_m old_n return print(gcd( )now we can use this function to help reduce any fraction to put fraction in lowest termswe will divide the numerator and the denominator by their greatest common divisor sofor the fraction the greatest common divisor is dividing the top and the bottom by creates new fraction (see listing listing lowest term fractions def __add__(selfother_fraction)new_num self num*other_fraction den self den*other_fraction num new_den self den other_fraction den common gcd(new_numnew_denreturn fraction(new_num /commonnew_den /common introduction |
12,520 | figure an instance of the fraction class with two methods fraction( fraction( print( / our fraction object now has two very useful methods and looks like figure an additional group of methods that we need to include in our example fraction class will allow two fractions to compare themselves to one another assume we have two fraction objectsf and = will only be true if they are references to the same object two different objects with the same numerators and denominators would not be equal under this implementation this is called shallow equality (see figure we can create deep equality (see figure equality by the same valuenot the same reference by overriding the __eq__ method the __eq__ method is another standard method available in any class the __eq__ method compares two objects and returns true if their values are the samefalse otherwise in the fraction classwe can implement the __eq__ method by again putting the two fractions in common terms and then comparing the numerators (see listing it is important to note that there are other relational operators that can be overridden for examplethe __le__ method provides the less than or equal functionality listing checking if two fractions are equal def __eq__(selfother)first_num self num other den second_num other num self den return first_num =second_num the complete fraction classup to this pointis shown below we leave the remaining arithmetic and relational methods as exercises review of basic python |
12,521 | figure shallow equality versus deep equality introduction |
12,522 | gcd function def gcd(mn)while ! old_m old_n old_n old_m old_n return fraction class implementsaddition and equality to domultiplicationdivisionsubtraction and comparison operators (class fractiondef __init__(selftopbottom)self num top self den bottom def __str__(self)return str(self num"/str(self dendef show(self)print(self num"/"self dendef __add__(selfother_fraction)new_num self num other_fraction den self den other_fraction num new_den self den other_fraction den common gcd(new_numnew_denreturn fraction(new_num /commonnew_den /commondef __eq__(selfother)first_num self num other den second_num other num self den return first_num =second_num fraction( fraction( print( yprint( =yself check to make sure you understand how operators are implemented in python classesand how to properly write methodswrite some methods to implement */and also implement comparison operators and review of basic python |
12,523 | summary computer science is the study of problem solving computer science uses abstraction as tool for representing both processes and data abstract data types allow programmers to manage the complexity of problem domain by hiding the details of the data python is powerfulyet easy-to-useobject-oriented language liststuplesand strings are built in python sequential collections dictionaries and sets are nonsequential collections of data classes allow programmers to implement abstract data types programmers can override standard methods as well as create new methods class constructor should always invoke the constructor of its parent before continuing on with its own data and behavior key terms abstract data type class data structure dictionary format operator information hiding method procedural abstraction self string abstraction computable data type encapsulation formatted strings list mutability programming shallow equality truth table algorithm data abstraction deep equality exception implementation-independent list comprehension object prompt simulation programming exercises implement the simple methods get_num and get_den that will return the numerator and denominator of fraction in many ways it would be better if all fractions were maintained in lowest terms right from the start modify the constructor for the fraction class so that gcd is used to reduce fractions immediately notice that this means the __add__ function no longer needs to reduce make the necessary modifications implement the remaining simple arithmetic operators (__sub____mul__and __truediv__ implement the remaining relational operators (__gt____ge____lt____le__and __ne__ introduction |
12,524 | modify the constructor for the fraction class so that it checks to make sure that the numerator and denominator are both integers if either is not an integer the constructor should raise an exception in the definition of fractions we assumed that negative fractions have negative numerator and positive denominator using negative denominator would cause some of the relational operators to give incorrect results in generalthis is an unnecessary constraint modify the constructor to allow the user to pass negative denominator so that all of the operators continue to work properly research the __radd__ method how does it differ from __add__when is it usedimplement __radd__ repeat the last question but this time consider the __iadd__ method research the __repr__ method how does it differ from __str__when is it usedimplement __repr__ design class to represent playing card now design class to represent deck of cards using these two classesimplement favorite card game find sudoku puzzle in the local newspaper write program to solve the puzzle programming exercises |
12,525 | introduction |
12,526 | two algorithm analysis objectives to understand why algorithm analysis is important to be able to use "big-oto describe execution time to understand the "big-oexecution time of common operations on python lists and dictionaries to understand how the implementation of python data impacts algorithm analysis to understand how to benchmark simple python programs what is algorithm analysisit is very common for beginning computer science students to compare their programs with one another you may also have noticed that it is common for computer programs to look very similarespecially the simple ones an interesting question often arises when two programs solve the same problem but look differentis one program better than the otherin order to answer this questionwe need to remember that there is an important difference between program and the underlying algorithm that the program is representing as we stated in an algorithm is genericstep-by-step list of instructions for solving problem it is method for solving any instance of the problem such that given particular inputthe algorithm produces the desired result programon the other handis an algorithm that has been encoded into some programming language there may be many programs for the same algorithmdepending on the programmer and the programming language being used to explore this difference furtherconsider the function shown below this function solves familiar problemcomputing the sum of the first integers the algorithm uses the idea of an accumulator variable that is initialized to the solution then iterates through the integersadding each to the accumulator def sum_of_n( )the_sum for in range( , + ) |
12,527 | the_sum the_sum return the_sum print(sum_of_n( )now look at the function foo below at first glance it may look strangebut upon further inspection you can see that this function is essentially doing the same thing as the previous one the reason this is not obvious is poor coding we did not use good identifier names to assist with readabilityand we used an extra assignment statement during the accumulation step that was not really necessary def foo(tom)fred for bill in range( tom+ )barney bill fred fred barney return fred print(foo( )the question we raised earlier asked whether one function is better than another the answer depends on your criteria the function sum_of_n is certainly better than the function foo if you are concerned with readability in factyou have probably seen many examples of this in your introductory programming course since one of the goals there is to help you write programs that are easy to read and easy to understand in this coursehoweverwe are also interested in characterizing the algorithm itself (we certainly hope that you will continue to strive to write readableunderstandable code algorithm analysis is concerned with comparing algorithms based upon the amount of computing resources that each algorithm uses we want to be able to consider two algorithms and say that one is better than the other because it is more efficient in its use of those resources or perhaps because it simply uses fewer from this perspectivethe two functions above seem very similar they both use essentially the same algorithm to solve the summation problem at this pointit is important to think more about what we really mean by computing resources there are two different ways to look at this one way is to consider the amount of space or memory an algorithm requires to solve the problem the amount of space required by problem solution is typically dictated by the problem instance itself every so oftenhoweverthere are algorithms that have very specific space requirementsand in those cases we will be very careful to explain the variations as an alternative to space requirementswe can analyze and compare algorithms based on the amount of time they require to execute this measure is sometimes referred to as the "execution timeor "running timeof the algorithm one way we can measure the execution time for the function sum_of_n is to do benchmark analysis this means that we will track the actual time required for the program to compute its result in pythonwe can benchmark function by noting the starting time and ending time with respect to the system we are using in the time module there is function called time that will return the current system clock time algorithm analysis |
12,528 | in seconds since some arbitrary starting point by calling this function twiceat the beginning and at the endand then computing the differencewe can get an exact number of seconds (fractions in most casesfor execution import time def sum_of_n_ ( )start time time(the_sum for in range( + )the_sum the_sum end time time(return the_sum,end-start this code shows the original sum_of_n function with the timing calls embedded before and after the summation the function returns tuple consisting of the result and the amount of time (in secondsrequired for the calculation if we perform invocations of the functioneach computing the sum of the first integerswe get the followingfor in range( )print("sum is % required % secondssum_of_n_ ( )sum is required seconds sum is required seconds sum is required seconds sum is required seconds sum is required seconds againthe time required for each runalthough longeris very consistentaveraging about times more seconds for equal to we getfor in range( )print("sum is % required % secondssum_of_n_ ( )sum is required seconds sum is required seconds sum is required seconds sum is required seconds sum is required seconds in this casethe average again turns out to be about times the previous now consider the following codewhich shows different means of solving nthe summation problem this functionsum_of_n_ takes advantage of closed equation = ( )( + what is algorithm analysis |
12,529 | to compute the sum of the first integers without iterating def sum_of_n_ ( )return ( ( ) print(sum_of_n_ ( )we do the same benchmark measurement for sum_of_n_ using five different values for ( and )we get the following resultssum is required seconds sum is required seconds sum is required seconds sum is required seconds sum is required seconds there are two important things to notice about this output firstthe times recorded above are shorter than any of the previous examples secondthey are very consistent no matter what the value of it appears that sum_of_n_ is hardly impacted by the number of integers being added but what does this benchmark really tell usintuitivelywe can see that the iterative solutions seem to be doing more work since some program steps are being repeated this is likely the reason it is taking longer alsothe time required for the iterative solution seems to increase as we increase the value of howeverthere is problem if we ran the same function on different computer or used different programming languagewe would likely get different results it could take even longer to perform sum_of_n_ if the computer were older we need better way to characterize these algorithms with respect to execution time the benchmark technique computes the actual time to execute it does not really provide us with useful measurementbecause it is dependent on particular machineprogramtime of daycompilerand programming language insteadwe would like to have characterization that is independent of the program or computer being used this measure would then be useful for judging the algorithm alone and could be used to compare algorithms across implementations big- notation when trying to characterize an algorithm' efficiency in terms of execution time,independent of any particular program or computerit is important to quantify the number of operations or steps that the algorithm will require if each of these steps is considered to be basic unit of computationthen the execution time for an algorithm can be expressed as the number of steps required to solve the problem deciding on an appropriate basic unit of computation can be complicated problem and will depend on how the algorithm is implemented good basic unit of computation for comparing the summation algorithms shown earlier might be to count the number of assignment statements performed to compute the sum in the function sum_of_nthe number of assignment statements is (the_sum plus the value of (the number of times we perform the_sum=the_sum+iwe can denote this by functioncall it algorithm analysis |
12,530 | where ( the parameter is often referred to as the "size of the problem,and we can read this as " (nis the time it takes to solve problem of size nnamely steps in the summation functions given aboveit makes sense to use the number of terms in the summation to denote the size of the problem we can then say that the sum of the first integers is bigger instance of the summation problem than the sum of the first because of thisit might seem reasonable that the time required to solve the larger case would be greater than for the smaller case our goal then is to show how the algorithm' execution time changes with respect to the size of the problem computer scientists prefer to take this analysis technique one step further it turns out that the exact number of operations is not as important as determining the most dominant part of the (nfunction in other wordsas the problem gets largersome portion of the (nfunction tends to overpower the rest this dominant term is whatin the endis used for comparison the order of magnitude function describes the part of (nthat increases the fastest as the value of increases order of magnitude is often called big- notation (for "order"and written as ( ( )it provides useful approximation to the actual number of steps in the computation the function (nprovides simple representation of the dominant part of the original (nin the above examplet ( as gets largethe constant will become less and less significant to the final result if we are looking for an approximation for ( )then we can drop the and simply say that the running time is (nit is important to note that the is certainly significant for (nhoweveras gets largeour approximation will be just as accurate without it as another examplesuppose that for some algorithmthe exact number of steps is ( when is smallsay or the constant seems to be the dominant part of the function howeveras gets largerthe term becomes the most important in factwhen is really largethe other two terms become insignificant in the role that they play in determining the final result againto approximate (nas gets largewe can ignore the other terms and focus on in additionthe coefficient becomes insignificant as gets large we would say then that the function (nhas an order of magnitude (nn or simply that it is ( although we do not see this in the summation examplesometimes the performance of an algorithm depends on the exact values of the data rather than simply the size of the problem for these kinds of algorithms we need to characterize their performance in terms of best caseworst caseor average case performance the worst case performance refers to particular data set where the algorithm performs especially poorly whereas different data set for the exact same algorithm might have extraordinarily good performance howeverin most cases the algorithm performs somewhere in between these two extremes (average caseit is important for computer scientist to understand these distinctions so they are not misled by one particular case number of very common order of magnitude functions will come up over and over as you study algorithms these are shown in table in order to decide which of these functions is the dominant part of any (nfunctionwe must see how they compare with one another as gets large figure shows graphs of the common functions from table notice that when is small what is algorithm analysis |
12,531 | (nname constant log logarithmic linear log log linear quadratic cubic exponential table common functions for big- figure plot of common big- functions the functions are not very well defined with respect to one another it is hard to tell which is dominant howeveras growsthere is definite relationship and it is easy to see how they compare with one another as final examplesuppose that we have the fragment of python code shown below although this program does not really do anythingit is instructive to see how we can take actual code and analyze performance for in range( )for in range( ) algorithm analysis |
12,532 | figure comparing (nwith common big- functions for in range( ) the number of assignment operations is the sum of four terms the first term is the constant representing the three assignment statements at the start of the fragment the second term is since there are three statements that are performed times due to the nested iteration the third term is ntwo statements iterated times finallythe fourth term is the constant representing the final assignment statement this gives us ( by looking at the exponentswe can easily see that the term will be dominant and therefore this fragment of code is ( note that all of the other terms as well as the coefficient on the dominant term can be ignored as grows larger figure shows few of the common big- functions as they compare with the (nfunction discussed above note that (nis initially larger than the cubic function howeveras growsthe cubic function quickly overtakes (nit is easy to see that (nthen follows the quadratic function as continues to grow self check write two python functions to find the minimum number in list the first function should compare each number to every other number on the list ( the second function should be linear ( what is algorithm analysis |
12,533 | an anagram detection example good example problem for showing algorithms with different orders of magnitude is the classic anagram detection problem for strings one string is an anagram of another if the second is simply rearrangement of the first for example'heartand 'earthare anagrams the strings 'pythonand 'typhonare anagrams as well for the sake of simplicitywe will assume that the two strings in question are of equal length and that they are made up of symbols from the set of lowercase alphabetic characters our goal is to write boolean function that will take two strings and return whether they are anagrams solution checking off our first solution to the anagram problem will check to see that each character in the first string actually occurs in the second if it is possible to "checkoffeach characterthen the two strings must be anagrams checking off character will be accomplished by replacing it with the special python value none howeversince strings in python are immutablethe first step in the process will be to convert the second string to list each character from the first string can be checked against the characters in the list and if foundchecked off by replacement def anagram_solution ( , )a_list list( pos still_ok true while pos len( and still_okpos found false while pos len(a_listand not foundif [pos =a_list[pos ]found true elsepos pos if founda_list[pos none elsestill_ok false pos pos return still_ok print(anagram_solution ('abcd','dcba')to analyze this algorithmwe need to note that each of the characters in will cause an iteration through up to characters in the list from each of the positions in the list will be visited once to match character from the number of visits then becomes the sum of algorithm analysis |
12,534 | the integers from to we stated earlier that this can be written as ii= ( as gets largethe term will dominate the term and the can be ignored thereforethis solution is ( solution sort and compare another solution to the anagram problem will make use of the fact that even though and are differentthey are anagrams only if they consist of exactly the same characters soif we begin by sorting each string alphabeticallyfrom to zwe will end up with the same string if the original two strings are anagrams the code below shows this solution againin python we can use the built-in sort method on lists by simply converting each string to list at the start def anagram_solution ( , )a_list list( a_list list( a_list sort(a_list sort(pos matches true while pos len( and matchesif a_list [pos=a_list [pos]pos pos elsematches false return matches print(anagram_solution ('abcde','edcba')at first glance you may be tempted to think that this algorithm is ( )since there is one simple iteration to compare the characters after the sorting process howeverthe two calls to the python sort method are not without their own cost as we will see in later sorting is typically either ( or ( log )so the sorting operations dominate the iteration in the endthis algorithm will have the same order of magnitude as that of the sorting process solution brute force brute force technique for solving problem typically tries to exhaust all possibilities for the anagram detection problemwe can simply generate list of all possible strings using the what is algorithm analysis |
12,535 | characters from and then see if occurs howeverthere is difficulty with this approach when generating all possible strings from there are possible first charactersn- possible characters for the second positionn for the thirdand so on the total number of candidate strings is ( ( which is nalthough some of the strings may be duplicatesthe program cannot know this ahead of time and so it will still generate ndifferent strings it turns out that ngrows even faster than as gets large in factif were characters longthere would be possible candidate strings if we processed one possibility every secondit would still take us years to go through the entire list this is probably not going to be good solution solution count and compare our final solution to the anagram problem takes advantage of the fact that any two anagrams will have the same number of 'sthe same number of 'sthe same number of 'sand so on in order to decide whether two strings are anagramswe will first count the number of times each character occurs since there are possible characterswe can use list of countersone for each possible character each time we see particular characterwe will increment the counter at that position in the endif the two lists of counters are identicalthe strings must be anagrams def anagram_solution ( ) [ [ for in range(len( ))pos ord( [ ]ord(' ' [posc [pos for in range(len( ))pos ord( [ ]ord(' ' [posc [pos still_ok true while and still_okif [ = [ ] elsestill_ok false return still_ok print(anagram_solution ('apple','pleap')againthe solution has number of iterations howeverunlike the first solutionnone of them are nested the first two iterations used to count the characters are both based on the third iterationcomparing the two lists of countsalways takes steps since there are possible algorithm analysis |
12,536 | characters in the strings adding it all up gives us ( steps that is (nwe have found linear order of magnitude algorithm for solving this problem before leaving this examplewe need to say something about space requirements although the last solution was able to run in linear timeit could only do so by using additional storage to keep the two lists of character counts in other wordsthis algorithm sacrificed space in order to gain time this is common occurrence on many occasions you will need to make decisions between time and space trade-offs in this casethe amount of extra space is not significant howeverif the underlying alphabet had millions of charactersthere would be more concern as computer scientistwhen given choice of algorithmsit will be up to you to determine the best use of computing resources given particular problem self check - given the following code fragmentwhat is its big- running timetest for in range( )for in range( )test test ( ( (log ( - given the following code fragment what is its big- running timetest for in range( )test test for in range( )test test ( ( (log ( - given the following code fragment what is its big- running timei while / what is algorithm analysis |
12,537 | ( ( (log ( performance of python data structures now that you have general idea of big- notation and the differences between the different functionsour goal in this section is to tell you about the big- performance for the operations on python lists and dictionaries we will then show you some timing experiments that illustrate the costs and benefits of using certain operations on each data structure it is important for you to understand the efficiency of these python data structures because they are the building blocks we will use as we implement other data structures in the remainder of the book in this section we are not going to explain why the performance is what it is in later you will see some possible implementations of both lists and dictionaries and how the performance depends on the implementation lists the designers of python had many choices to make when they implemented the list data structure each of these choices could have an impact on how fast list operations perform to help them make the right choices they looked at the ways that people would most commonly use the list data structure and they optimized their implementation of list so that the most common operations were very fast of course they also tried to make the less common operations fastbut when tradeoff had to be made the performance of less common operation was often sacrificed in favor of the more common operation two common operations are indexing and assigning to an index position both of these operations take the same amount of time no matter how large the list becomes when an operation like this is independent of the size of the list they are ( another very common programming task is to grow list there are two ways to create longer list you can use the append method or the concatenation operator the append method is ( howeverthe concatenation operator is (kwhere is the size of the list that is being concatenated this is important for you to know because it can help you make your own programs more efficient by choosing the right tool for the job let us look at four different ways we might generate list of numbers starting with first we will try for loop and create the list by concatenationthen we will use append rather than concatenation nextwe will try creating the list using list comprehension and finallyand perhaps the most obvious wayusing the range function wrapped by call to the list constructor the following code shows making our list in four different ways def test () [ algorithm analysis |
12,538 | for in range( ) [idef test () [for in range( ) append(idef test () [ for in range( )def test () list(range( )to capture the time it takes for each of our functions to execute we will use python' timeit module the timeit module is designed to allow python developers to make cross-platform timing measurements by running functions in consistent environment and using timing mechanisms that are as similar as possible across operating systems to use timeit you create timer object whose parameters are two python statements the first parameter is python statement that you want to timethe second parameter is statement that will run once to set up the test the timeit module will then time how long it takes to execute the statement some number of times by default timeit will try to run the statement one million times when its done it returns the time as floating point value representing the total number of seconds howeversince it executes the statement million times you can read the result as the number of microseconds to execute the test one time you can also pass timeit named parameter called number that allows you to specify how many times the test statement is executed the following session shows how long it takes to run each of our test functions times import the timeit module import timeit import the timer class defined in the module from timeit import timer if the above line is excludedyou need to replace timer with timeit timer when defining timer object timer("test ()""from __main__ import test "print("concat ", timeit(number= )"milliseconds" timer("test ()""from __main__ import test "print("append ", timeit(number= )"milliseconds" timer("test ()""from __main__ import test "print("comprehension ", timeit(number= )"milliseconds" timer("test ()""from __main__ import test "print("list range ", timeit(number= )"milliseconds"concat milliseconds append milliseconds comprehension milliseconds list range milliseconds performance of python data structures |
12,539 | in the experiment above the statement that we are timing is the function call to test ()test ()and so on the setup statement may look very strange to youso let us consider it in more detail you are probably very familiar with the fromimport statementbut this is usually used at the beginning of python program file in this case the statement from __main__ import test imports the function test from the __main__ namespace into the namespace that timeit sets up for the timing experiment the timeit module does this because it wants to run the timing tests in an environment that is uncluttered by any stray variables you may have createdthat may interfere with your function' performance in some unforeseen way from the experiment above it is clear that the append operation at milliseconds is much faster than concatenation at milliseconds in the above experiment we also show the times for two additional methods for creating listusing the list constructor with call to range and list comprehension it is interesting to note that the list comprehension is twice as fast as for loop with an append operation one final observation about this little experiment is that all of the times that you see above include some overhead for actually calling the test functionbut we can assume that the function call overhead is identical in all four cases so we still get meaningful comparison of the operations so it would not be accurate to say that the concatenation operation takes milliseconds but rather the concatenation test function takes milliseconds as an exercise you could test the time it takes to call an empty function and subtract that from the numbers above now that we have seen how performance can be measured concretely you can look at table to see the big- efficiency of all the basic list operations after thinking carefully about table you may be wondering about the two different times for pop when pop is called on the end of the list it takes ( but when pop is called on the first element in the list or anywhere in the middle it is (nthe reason for this lies in how python chooses to implement lists when an item is taken from the front of the listin python' implementationall the other elements in the list are shifted one position closer to the beginning this may seem silly to you nowbut if you look at table you will see that this implementation also allows the index operation to be ( this is tradeoff that the python implementors thought was good one as way of demonstrating this difference in performance let us do another experiment using the timeit module our goal is to be able to verify the performance of the pop operation on list of known size when the program pops from the end of the listand again when the program pops from the beginning of the list we will also want to measure this time for lists of different sizes what we would expect to see is that the time required to pop from the end of the list will stay constant even as the list grows in sizewhile the time to pop from the beginning of the list will continue to increase as the list grows the code below shows one attempt to measure the difference between the two uses of pop as you can see from this first examplepopping from the end takes millisecondswhereas popping from the beginning takes milliseconds for list of two million elements this is factor of there are couple of things to notice about this code the first is the statement from __main__ import $xalthough we did not define function we do want to be able to use the list object in our test this approach allows us to time just the single pop statement and get the most accurate measure of the time for that single operation because the timer repeats algorithm analysis |
12,540 | operation indexx[index assignment append pop(pop(iinsert( ,itemdel operator iteration contains (inget slice [ :ydel slice set slice reverse concatenate sort multiply big- efficiency ( ( ( ( (no(no(no(no(no(ko(no( ko(no(ko( log no(nktable big- efficiency of python list operators times it is also important to point out that the list is decreasing in size by each time through the loop but since the initial list is two million elements in size we only reduce the overall size by pop_zero timer(" pop( )""from __main__ import "pop_end timer(" pop()""from __main__ import " list(range( )pop_zero timeit(number= list(range( )pop_end timeit(number= while our first test does show that pop( is indeed slower than pop()it does not validate the claim that pop( is (nwhile pop(is ( to validate that claim we need to look at the performance of both calls over range of list sizes pop_zero timer(" pop( )""from __main__ import "pop_end timer(" pop()""from __main__ import "print("pop( pop()"for in range( , , ) list(range( )pt pop_end timeit(number= list(range( ) performance of python data structures |
12,541 | figure comparing the performance of pop and pop( pz pop_zero timeit(number= print("% % %(pz,pt)figure shows the results of our experiment you can see that as the list gets longer and longer the time it takes to pop( also increases while the time for pop stays very flat this is exactly what we would expect to see for (nand ( algorithm some sources of error in our little experiment include the fact that there are other processes running on the computer as we measure that may slow down our codeso even though we try to minimize other things happening on the computer there is bound to be some variation in time that is why the loop runs the test one thousand times in the first place to statistically gather enough information to make the measurement reliable dictionaries the second major python data structure is the dictionary as you probably recalldictionaries differ from lists in that you can access items in dictionary by key rather than position later in this book you will see that there are many ways to implement dictionary the thing that is most important to notice right now is that the get item and set item operations on dictionary are ( another important dictionary operation is the contains operation checking to see whether key is in the dictionary or not is also ( the efficiency of all dictionary operations algorithm analysis |
12,542 | operation big- efficiency copy (nget item ( set item ( delete item ( contains (ino( iteration (ntable big- efficiency of python dictionary operations is summarized in table one important side note on dictionary performance is that the efficiencies we provide in the table are for average performance in some rare cases the containsget itemand set item operations can degenerate into (nperformance but we will get into that in later when we talk about the different ways that dictionary could be implemented for our last performance experiment we will compare the performance of the contains operation between lists and dictionaries in the process we will confirm that the contains operator for lists is (nand the contains operator for dictionaries is ( the experiment we will use to compare the two is simple we'll make list with range of numbers in it then we will pick numbers at random and check to see if the numbers are in the list if our performance tables are correct the bigger the list the longer it should take to determine if any one number is contained in the list we will repeat the same experiment for dictionary that contains numbers as the keys in this experiment we should see that determining whether or not number is in the dictionary is not only much fasterbut the time it takes to check should remain constant even as the dictionary grows larger the code below implements this comparison notice that we are performing exactly the same operationnumber in container the difference is that on line is listand on line is dictionary import timeit import random for in range( , , ) timeit timer("random randrange(%din "% "from __main__ import random, " list(range( )lst_time timeit(number= { :none for in range( )d_time timeit(number= print("% ,% ,% (ilst_timed_time)figure summarizes the results you can see that the dictionary is consistently faster for the smallest list size of elements dictionary is times faster than list for the largest list size of elements the dictionary is times fasteryou can also see that the time it takes for the contains operator on the list grows linearly with the size of the list this verifies the assertion that the contains operator on list is (nit can also be seen that the performance of python data structures |
12,543 | figure comparing the in operator for python lists and dictionaries time for the contains operator on dictionary is constant even as the dictionary size grows in fact for dictionary size of the contains operation took milliseconds and for the dictionary size of it also took milliseconds since python is an evolving languagethere are always changes going on behind the scenes the latest information on the performance of python data structures can be found on the python website as of this writing the python wiki has nice time complexity page that can be found at the time complexity wiki self check - which of the above list operations is not ( ) list pop( list pop( list append( list[ all of the above are ( - which of the above dictionary operations is ( ) algorithm analysis |
12,544 | 'xin my_dict del my_dict[' ' my_dict[' '= my_dict[' 'my_dict[' ' all of the above are ( summary algorithm analysis is an implementation-independent way of measuring an algorithm big- notation allows algorithms to be classified by their dominant process with respect to the size of the problem key terms average case checking off log linear quadratic big- notation exponential logarithmic time complexity brute force linear order of magnitude worst case discussion questions give the big- performance of the following code fragmentfor in range( )for in range( ) give the big- performance of the following code fragmentfor in range( ) give the big- performance of the following code fragmenti while / give the big- performance of the following code fragment summary |
12,545 | for in range( )for in range( )for in range( ) give the big- performance of the following code fragmenti while / give the big- performance of the following code fragmentfor in range( ) for in range( ) for in range( ) programming exercises devise an experiment to verify that the list index operator is ( devise an experiment to verify that get item and set item are ( for dictionaries devise an experiment that compares the performance of the del operator on lists and dictionaries given list of numbers in random order write linear time algorithm to find the kth smallest number in the list explain why your algorithm is linear can you improve the algorithm from the previous problem to be ( log( )) algorithm analysis |
12,546 | three basic data structures objectives to understand the abstract data types stackqueuedequeand list to be able to implement the adts stackqueueand deque using python lists to understand the performance of the implementations of basic linear data structures to understand prefixinfixand postfix expression formats to use stacks to evaluate postfix expressions to use stacks to convert expressions from infix to postfix to use queues for basic timing simulations to be able to recognize problem properties where stacksqueuesand deques are appropriate data structures to be able to implement the abstract data type list as linked list using the node and reference pattern to be able to compare the performance of our linked list implementation with python' list implementation what are linear structureswe will begin our study of data structures by considering four simple but very powerful concepts stacksqueuesdequesand lists are examples of data collections whose items are ordered depending on how they are added or removed once an item is addedit stays in that position relative to the other elements that came before and came after it collections such as these are often referred to as linear data structures linear structures can be thought of as having two ends sometimes these ends are referred to as the "leftand the "rightor in some cases the "frontand the "rear you could also call them the "topand the "bottom the names given to the ends are not significant what distinguishes one linear structure from another is the way in which items are added and removedin particular the location where these additions and removals occur for examplea structure might allow |
12,547 | figure stack of books new items to be added at only one end some structures might allow items to be removed from either end these variations give rise to some of the most useful data structures in computer science they appear in many algorithms and can be used to solve variety of important problems stacks what is stacka stack (sometimes called "push-down stack"is an ordered collection of items where the addition of new items and the removal of existing items always takes place at the same end this end is commonly referred to as the "top the end opposite the top is known as the "base the base of the stack is significant since items stored in the stack that are closer to the base represent those that have been in the stack the longest the most recently added item is the one that is in position to be removed first this ordering principle is sometimes called lifolast-in first-out it provides an ordering based on length of time in the collection newer items are near the topwhile older items are near the base many examples of stacks occur in everyday situations almost any cafeteria has stack of trays or plates where you take the one at the topuncovering new tray or plate for the next customer in line imagine stack of books on desk (figure the only book whose cover is visible is the one on top to access others in the stackwe need to remove the ones that are sitting on top of them figure shows another stack this one contains number of primitive python data objects one of the most useful ideas related to stacks comes from the simple observation of items as they are added and then removed assume you start out with clean desktop now place books one at time on top of each other you are constructing stack consider what happens when you begin removing books the order that they are removed is exactly the reverse of the order that they were placed stacks are fundamentally importantas they can be used to reverse the order of items the order of insertion is the reverse of the order of removal figure shows the python data object stack as it was created and then again as items are removed note the order of the objects considering this reversal propertyyou can perhaps think of examples of stacks that occur as basic data structures |
12,548 | figure stack of primitive python objects figure the reversal property of stacks stacks |
12,549 | stack operation stack contents return value is_empty( push( push('dog' peek( push(trues size( is_empty( push( pop( pop( size([[ [ ,'dog'[ ,'dog'[ ,'dog',true[ ,'dog',true[ ,'dog',true[ ,'dog',true, [ ,'dog',true[ ,'dog'[ ,'dog'true 'dog false true table sample stack operations you use your computer for exampleevery web browser has back button as you navigate from web page to web pagethose pages are placed on stack (actually it is the urls that are going on the stackthe current page that you are viewing is on the top and the first page you looked at is at the base if you click on the back buttonyou begin to move in reverse order through the pages the stack abstract data type the stack abstract data type is defined by the following structure and operations stack is structuredas described aboveas an ordered collection of items where items are added to and removed from the end called the "top stacks are ordered lifo the stack operations are given below stack(creates new stack that is empty it needs no parameters and returns an empty stack push(itemadds new item to the top of the stack it needs the item and returns nothing pop(removes the top item from the stack it needs no parameters and returns the item the stack is modified peek(returns the top item from the stack but does not remove it it needs no parameters the stack is not modified is_empty(tests to see whether the stack is empty it needs no parameters and returns boolean value size(returns the number of items on the stack it needs no parameters and returns an integer for exampleif is stack that has been created and starts out emptythen table shows the results of sequence of stack operations under stack contentsthe top item is listed at the far right basic data structures |
12,550 | implementing stack in python now that we have clearly defined the stack as an abstract data type we will turn our attention to using python to implement the stack recall that when we give an abstract data type physical implementation we refer to the implementation as data structure as we described in in pythonas in any object-oriented programming languagethe implementation of choice for an abstract data type such as stack is the creation of new class the stack operations are implemented as methods furtherto implement stackwhich is collection of elementsit makes sense to utilize the power and simplicity of the primitive collections provided by python we will use list recall that the list class in python provides an ordered collection mechanism and set of methods for exampleif we have the list [ ]we need only to decide which end of the list will be considered the top of the stack and which will be the base once that decision is madethe operations can be implemented using the list methods such as append and pop the following stack implementation assumes that the end of the list will hold the top element of the stack as the stack grows (as push operations occur)new items will be added on the end of the list pop operations will manipulate that same end completed implementation of stack adt class stackdef __init__(self)self items [def is_empty(self)return self items =[def push(selfitem)self items append(itemdef pop(self)return self items pop(def peek(self)return self items[len(self items)- def size(self)return len(self itemsremember that nothing happens when we click the run button other than the definition of the class we must create stack object and then use it shows the stack class in action as we perform the sequence of operations from table stack(print( is_empty() push( push('dog' the stack abstract data type |
12,551 | print( peek() push(trueprint( size()print( is_empty() push( print( pop()print( pop()print( size()it is important to note that we could have chosen to implement the stack using list where the top is at the beginning instead of at the end in this casethe previous pop and append methods would no longer work and we would have to index position (the first item in the listexplicitly using pop and insert the implementation is shown below class stackdef __init__(self)self items [def is_empty(self)return self items =[def push(selfitem)self items insert( itemdef pop(self)return self items pop( def peek(self)return self items[ def size(self)return len(self itemss stack( push('hello' push('true'print( pop()this ability to change the physical implementation of an abstract data type while maintaining the logical characteristics is an example of abstraction at work howevereven though the stack will work either wayif we consider the performance of the two implementationsthere is definitely difference recall that the append and pop(operations were both ( this means that the first implementation will perform push and pop in constant time no matter how many items are on the stack the performance of the second implementation suffers in that the insert( and pop( operations will both require (nfor stack of size clearlyeven though the implementations are logically equivalentthey would have very different timings when performing benchmark testing basic data structures |
12,552 | self check given the following sequence of stack operationswhat is the top item on the stack when the sequence is completem stack( push(' ' push(' ' pop( push(' ' peek( ' ' ' the stack is empty given the following sequence of stack operationswhat is the top item on the stack when the sequence is completem stack( push(' ' push(' ' push(' 'while not is_empty() pop( pop( ' the stack is empty an error will occur 'zwrite function rev_string(my_strthat uses stack to reverse the characters in string simple balance parentheses we now turn our attention to using stacks to solve real computer science problems you have no doubt written arithmetic expressions such as ( ( )/( where parentheses are used to order the performance of operations you may also have some experience programming in language such as lisp with constructs like (defun square( ( ) the stack abstract data type |
12,553 | figure matching parentheses this defines function called square that will return the square of its argument lisp is notorious for using lots and lots of parentheses in both of these examplesparentheses must appear in balanced fashion balanced parentheses means that each opening symbol has corresponding closing symbol and the pairs of parentheses are properly nested consider the following correctly balanced strings of parentheses(()()()()(((()))(()((())())compare those with the followingwhich are not balanced((((((()())(()()((the ability to differentiate between parentheses that are correctly balanced and those that are unbalanced is an important part of recognizing many programming language structures the challenge then is to write an algorithm that will read string of parentheses from left to right and decide whether the symbols are balanced to solve this problem we need to make an important observation as you process symbols from left to rightthe most recent opening parenthesis must match the next closing symbol (see figure alsothe first opening symbol processed may have to wait until the very last symbol for its match closing symbols match opening symbols in the reverse order of their appearancethey match from the inside out this is clue that stacks can be used to solve the problem once you agree that stack is the appropriate data structure for keeping the parenthesesthe statement of the algorithm is straightforward starting with an empty stackprocess the parenthesis strings from left to right if symbol is an opening parenthesispush it on the stack as signal that corresponding closing symbol needs to appear later ifon the other handa symbol is closing parenthesispop the stack as long as it is possible to pop the stack to match every closing symbolthe parentheses remain balanced if at any time there is no opening symbol on the stack to match closing symbolthe string is not balanced prop basic data structures |
12,554 | erly at the end of the stringwhen all symbols have been processedthe stack should be empty import stack #import the stack class as previously defined def par_checker(symbol_string) stack(balanced true index while index len(symbol_stringand balancedsymbol symbol_string[indexif symbol ="(" push(symbolelseif is_empty()balanced false elses pop( index index if balanced and is_empty()return true elsereturn false print(par_checker('((()))')print(par_checker('(()')this functionpar_checkerassumes that stack class is available and returns boolean result as to whether the string of parentheses is balanced note that the boolean variable balanced is initialized to true as there is no reason to assume otherwise at the start if the current symbol is (then it is pushed on the stack (lines - note also in line that pop simply removes symbol from the stack the returned value is not used since we know it must be an opening symbol seen earlier at the end (lines - )as long as the expression is balanced and the stack has been completely cleaned offthe string represents correctly balanced sequence of parentheses balanced symbols ( general casehe balanced parentheses problem shown above is specific case of more general situation that arises in many programming languages the general problem of balancing and nesting different kinds of opening and closing symbols occurs frequently for examplein python square bracketsand ]are used for listscurly bracesand }are used for dictionariesand parenthesesand )are used for tuples and arithmetic expressions it is possible to mix symbols as long as each maintains its own open and close relationship strings of symbols such as the stack abstract data type |
12,555 | are properly balanced in that not only does each opening symbol have corresponding closing symbolbut the types of symbols match as well compare those with the following strings that are not balancedthe simple parentheses checker from the previous section can easily be extended to handle these new types of symbols recall that each opening symbol is simply pushed on the stack to wait for the matching closing symbol to appear later in the sequence when closing symbol does appearthe only difference is that we must check to be sure that it correctly matches the type of the opening symbol on top of the stack if the two symbols do not matchthe string is not balanced once againif the entire string is processed and nothing is left on the stackthe string is correctly balanced the python program to implement this is shown below the only change appears in line where we call helper functionmatchesto assist with symbol-matching each symbol that is removed from the stack must be checked to see that it matches the current closing symbol if mismatch occursthe boolean variable balanced is set to false import stack as previously defined completed extended par_checker for[,{,(,),}, def par_checker(symbol_string) stack(balanced true index while index len(symbol_stringand balancedsymbol symbol_string[indexif symbol in "([{" push(symbolelseif is_empty()balanced false elsetop pop(if not matches(topsymbol)balanced false index index basic data structures |
12,556 | if balanced and is_empty()return true elsereturn false def matches(openclose)opens "([{closes ")]}return opens index(open=closes index(close print(par_checker('{{([][])}()}')print(par_checker('[{()]')these two examples show that stacks are very important data structures for the processing of language constructs in computer science almost any notation you can think of has some type of nested symbol that must be matched in balanced order there are number of other important uses for stacks in computer science we will continue to explore them in the next sections converting decimal numbers to binary numbers in your study of computer scienceyou have probably been exposed in one way or another to the idea of binary number binary representation is important in computer science since all values stored within computer exist as string of binary digitsa string of and without the ability to convert back and forth between common representations and binary numberswe would need to interact with computers in very awkward ways integer values are common data items they are used in computer programs and computation all the time we learn about them in math class and of course represent them using the decimal number systemor base the decimal number and its corresponding binary equivalent are interpreted respectively as and but how can we easily convert integer values into binary numbersthe answer is an algorithm called "divide by that uses stack to keep track of the digits for the binary result the divide by algorithm assumes that we start with an integer greater than simple iteration then continually divides the decimal number by and keeps track of the remainder the first division by gives information as to whether the value is even or odd an even value will have remainder of it will have the digit in the ones place an odd value will have remainder of and will have the digit in the ones place we think about building our binary number as sequence of digitsthe first remainder we compute will actually be the last digit in the sequence as shown in figure we again see the reversal property that signals that stack is likely to be the appropriate data structure for solving the problem the python code in below implements the divide by algorithm the function divide_by_ takes an argument that is decimal number and repeatedly divides it by line uses the built-in modulo operator%to extract the remainder and line then pushes it on the stack after the division process reaches binary string is constructed in lines - line the stack abstract data type |
12,557 | figure decimal-to-binary conversion creates an empty string the binary digits are popped from the stack one at time and appended to the right-hand end of the string the binary string is then returned import stack as previously defined def divide_by_ (dec_number)rem_stack stack( while dec_number rem dec_number rem_stack push(remdec_number dec_number / bin_string "while not rem_stack is_empty()bin_string bin_string str(rem_stack pop() return bin_string print(divide_by_ ( )he algorithm for binary conversion can easily be extended to perform the conversion for any base in computer science it is common to use number of different encodings the most common of these are binaryoctal (base )and hexadecimal (base the decimal number and its corresponding octal and hexadecimal equivalents and are interpreted as and the function divide_by_ can be modified to accept not only decimal value but also base for the intended conversion the "divide by idea is simply replaced with more general "divide by base new function called base_convertershown belowtakes decimal number and any base between and as parameters the remainders are still pushed onto the stack until the value being converted becomes the same left-to-right string construction technique can be used with one slight change base through base basic data structures |
12,558 | numbers need maximum of digitsso the typical digit characters and work fine the problem comes when we go beyond base we can no longer simply use the remaindersas they are themselves represented as two-digit decimal numbers instead we need to create set of digits that can be used to represent those remainders beyond import stack as previously defined def base_converter(dec_numberbase)digits " abcdefrem_stack stack(while dec_number rem dec_number base rem_stack push(remdec_number dec_number /base new_string "while not rem_stack is_empty()new_string new_string digits[rem_stack pop()return new_string print(base_converter( )print(base_converter( ) solution to this problem is to extend the digit set to include some alphabet characters for examplehexadecimal uses the ten decimal digits along with the first six alphabet characters for the digits to implement thisa digit string is created that stores the digits in their corresponding positions is at position is at position is at position is at position and so on when remainder is removed from the stackit can be used to index into the digit string and the correct resulting digit can be appended to the answer for exampleif the remainder is removed from the stackthe digit is appended to the resulting string self check what is the value of expressed as an octal number what is the value of expressed as hexidecimal number what is the value of expressed in base infixprefixand postfix expressions when you write an arithmetic expression such as *cthe form of the expression provides you with information so that you can interpret it correctly in this case we know that the variable is being multiplied by the variable since the multiplication operator appears between them the stack abstract data type |
12,559 | in the expression this type of notation is referred to as infix since the operator is in between the two operands that it is working on consider another infix examplea the operators and still appear between the operandsbut there is problem which operands do they work ondoes the work on and or does the take and cthe expression seems ambiguous in factyou have been reading and writing these types of expressions for long time and they do not cause you any problem the reason for this is that you know something about the operators and each operator has precedence level operators of higher precedence are used before operators of lower precedence the only thing that can change that order is the presence of parentheses the precedence order for arithmetic operators places multiplication and division above addition and subtraction if two operators of equal precedence appearthen left-to-right ordering or associativity is used let' interpret the troublesome expression using operator precedence and are multiplied firstand is then added to that result ( bc would force the addition of and to be done first before the multiplication in expression cby precedence (via associativity)the leftmost would be done first although all this may be obvious to youremember that computers need to know exactly what operators to perform and in what order one way to write an expression that guarantees there will be no confusion with respect to the order of operations is to create what is called fully parenthesized expression this type of expression uses one pair of parentheses for each operator the parentheses dictate the order of operationsthere is no ambiguity there is also no need to remember any precedence rules the expression can be rewritten as (( ( )dto show that the multiplication happens firstfollowed by the leftmost addition can be written as ((( bcdsince the addition operations associate from left to right there are two other very important expression formats that may not seem obvious to you at first consider the infix expression what would happen if we moved the operator before the two operandsthe resulting expression would be +ab likewisewe could move the operator to the end we would get abthese look bit strange these changes to the position of the operator with respect to the operands create two new expression formatsprefix and postfix prefix expression notation requires that all operators precede the two operands that they work on postfixon the other handrequires that its operators come after the corresponding operands few more examples should help to make this bit clearer (see table would be written as + bc in prefix the multiplication operator comes immediately before the operands and cdenoting that has precedence over the addition operator then appears before the and the result of the multiplication in postfixthe expression would be abc againthe order of operations is preserved since the appears immediately after the and the cdenoting that has precedencewith coming after although the operators moved and now appear either before or after their respective operandsthe order of the operands stayed exactly the same relative to one another now consider the infix expression ( bc recall that in this caseinfix requires the parentheses to force the performance of the addition before the multiplication howeverwhen basic data structures |
12,560 | infix expression + + * prefix expression +ab + bc postfix expression ababc table examples of infixprefixand postfix infix expression ( bc prefix expression abc postfix expression ab ctable an expression with parentheses + was written in prefixthe addition operator was simply moved before the operands+ab the result of this operation becomes the first operand for the multiplication the multiplication operator is moved in front of the entire expressiongiving us abc likewisein postfix abforces the addition to happen first the multiplication can be done to that result and the remaining operand the proper postfix expression is then ab cconsider these three expressions again (see table something very important has happened where did the parentheses gowhy don' we need them in prefix and postfixthe answer is that the operators are no longer ambiguous with respect to the operands that they work on only infix notation requires the additional symbols the order of operations within prefix and postfix expressions is completely determined by the position of the operator and nothing else in many waysthis makes infix the least desirable notation to use table shows some additional examples of infix expressions and the equivalent prefix and postfix expressions be sure that you understand how they are equivalent in terms of the order of the operations being performed conversion of infix expressions to prefix and postfix so farwe have used ad hoc methods to convert between infix expressions and the equivalent prefix and postfix expression notations as you might expectthere are algorithmic ways to perform the conversion that allow any expression of any complexity to be correctly transformed the first technique that we will consider uses the notion of fully parenthesized expression that was discussed earlier recall that can be written as ( ( )to show explicitly that the multiplication has precedence over the addition on closer observationhoweveryou can see that each parenthesis pair also denotes the beginning and the end of an operand pair with the corresponding operator in the middle look at the right parenthesis in the subexpression ( cabove if we were to move the infix expression prefix expression + * + bcd ( ( dab cd * + * ab cd + + + +abcd postfix expression abc +dab cd ab cd ab dtable additional examples of infixprefixand postfix the stack abstract data type |
12,561 | figure moving operators to the right for postfix notationfigure moving operators to the left for prefix notationmultiplication symbol to that position and remove the matching left parenthesisgiving us bc*we would in effect have converted the subexpression to postfix notation if the addition operator were also moved to its corresponding right parenthesis position and the matching left parenthesis were removedthe complete postfix expression would result (see figure if we do the same thing but instead of moving the symbol to the position of the right parenthesiswe move it to the leftwe get prefix notation (see figure the position of the parenthesis pair is actually clue to the final position of the enclosed operator so in order to convert an expressionno matter how complexto either prefix or postfix notationfully parenthesize the expression using the order of operations then move the enclosed operator to the position of either the left or the right parenthesis depending on whether you want prefix or postfix notation here is more complex expression( bc ( ( gfigure shows the conversion to postfix and prefix notations general infix-to-postfix conversion we need to develop an algorithm to convert any infix expression to postfix expression to do this we will look closer at the conversion process consider once again the expression as shown aboveabc is the postfix equivalent we have already noted that the operands aband stay in their relative positions it is only the operators that change position let us look again at the operators in the infix expression the first operator that appears from left to right is howeverin the postfix expressionis at the end since the next operator*has precedence over addition the order figure converting complex expression to prefix and postfix notations basic data structures |
12,562 | of the operators in the original expression is reversed in the resulting postfix expression as we process the expressionthe operators have to be saved somewhere since their corresponding right operands are not seen yet alsothe order of these saved operators may need to be reversed due to their precedence this is the case with the addition and the multiplication in this example since the addition operator comes before the multiplication operator and has lower precedenceit needs to appear after the multiplication operator is used because of this reversal of orderit makes sense to consider using stack to keep the operators until they are needed what about ( bcrecall that ab cis the postfix equivalent againprocessing this infix expression from left to rightwe see first in this casewhen we see *has already been placed in the result expression because it has precedence over by virtue of the parentheses we can now start to see how the conversion algorithm will work when we see left parenthesiswe will save it to denote that another operator of high precedence will be coming that operator will need to wait until the corresponding right parenthesis appears to denote its position (recall the fully parenthesized techniquewhen that right parenthesis does appearthe operator can be popped from the stack as we scan the infix expression from left to rightwe will use stack to keep the operators this will provide the reversal that we noted in the first example the top of the stack will always be the most recently saved operator whenever we read new operatorwe will need to consider how that operator compares in precedence with the operatorsif anyalready on the stack assume the infix expression is string of tokens delimited by spaces the operator tokens are */+and -along with the left and right parenthesesand the operand tokens are the single-character identifiers abcand so on the following steps will produce string of tokens in postfix order create an empty stack called op_stack for keeping operators create an empty list for output convert the input infix string to list by using the string method split scan the token list from left to right if the token is an operandappend it to the end of the output list if the token is left parenthesispush it on the op_stack if the token is right parenthesispop the op_stack until the corresponding left parenthesis is removed append each operator to the end of the output list if the token is an operator*/+or -push it on the op_stack howeverfirst remove any operators already on the op_stack that have higher or equal precedence and append them to the output list when the input expression has been completely processedcheck the op_stack any operators still on the stack can be removed and appended to the end of the output list figure shows the conversion algorithm working on the expression note that the first operator is removed upon seeing the operator alsostays on the stack when the second occurssince multiplication has precedence over addition at the end of the the stack abstract data type |
12,563 | figure converting to postfix notationinfix expression the stack is popped twiceremoving both operators and placing as the last operator in the postfix expression in order to code the algorithm in pythonwe will use dictionary called prec to hold the precedence values for the operators this dictionary will map each operator to an integer that can be compared against the precedence levels of other operators (we have arbitrarily used the integers and the left parenthesis will receive the lowest value possible this way any operator that is compared against it will have higher precedence and will be placed on top of it line defines the operands to be any upper-case character or digit the complete conversion function is shown below import stack as previously defined def infix_to_postfix(infix_expr)prec {prec["*" prec["/" prec["+" prec["-" prec["(" op_stack stack(postfix_list [token_list infix_expr split( for token in token_listif token in "abcdefghijklmnopqrstuvwxyzor token in " "postfix_list append(tokenelif token ='('op_stack push(tokenelif token =')'top_token op_stack pop( basic data structures |
12,564 | while top_token !'('postfix_list append(top_tokentop_token op_stack pop(elsewhile (not op_stack is_empty()and (prec[op_stack peek()>prec[token])postfix_list append(op_stack pop()op_stack push(token while not op_stack is_empty()postfix_list append(op_stack pop()return join(postfix_list print(infix_to_postfix(" ")print(infix_to_postfix(" )") few more examples of execution in the python shell are shown below infix_to_postfix(" )"' *infix_to_postfix(" "' *infix_to_postfix(" "' +postfix evaluation as final stack examplewe will consider the evaluation of an expression that is already in postfix notation in this casea stack is again the data structure of choice howeveras you scan the postfix expressionit is the operands that must waitnot the operators as in the conversion algorithm above another way to think about the solution is that whenever an operator is seen on the inputthe two most recent operands will be used in the evaluation to see this in more detailconsider the postfix expression as you scan the expression from left to rightyou first encounter the operands and at this pointyou are still unsure what to do with them until you see the next symbol placing each on the stack ensures that they are available if an operator comes next in this casethe next symbol is another operand soas beforepush it and check the next symbol now we see an operatorthis means that the two most recent operands need to be used in multiplication operation by popping the stack twicewe can get the proper operands and then perform the multiplication (in this case getting the result we can now handle this result by placing it back on the stack so that it can be used as an operand for the later operators in the expression when the final operator is processedthere will be only one value left on the stack pop and return it as the result of the expression figure shows the stack contents as this entire example expression is being processed the stack abstract data type |
12,565 | figure sack contents during evaluationfigure more complex example of evaluationfigure shows slightly more complex example + +there are two things to note in this example firstthe stack size growsshrinksand then grows again as the subexpressions are evaluated secondthe division operation needs to be handled carefully recall that the operands in the postfix expression are in their original order since postfix changes only the placement of operators when the operands for the division are popped from the stackthey are reversed since division is not commutative operatorin other words / is not the same as / we must be sure that the order of the operands is not switched assume the postfix expression is string of tokens delimited by spaces the operators are */+and -and the operands are assumed to be single-digit integer values the output will be an integer result create an empty stack called operand_stack convert the string to list by using the string method split scan the token list from left to right if the token is an operandconvert it from string to an integer and push the value onto the operand_stack if the token is an operator*/+or -it will need two operands pop the operand_stack twice the first pop is the second operand and the second pop is the first operand perform the arithmetic operation push the result back on the operand_stack basic data structures |
12,566 | when the input expression has been completely processedthe result is on the stack pop the operand_stack and return the value the complete function for the evaluation of postfix expressions is shown below to assist with the arithmetica helper function do_math is defined that will take two operands and an operator and then perform the proper arithmetic operation import stack as previously defined def postfix_eval(postfix_expr)operand_stack stack(token_list postfix_expr split(for token in token_listif token in " "operand_stack push(int(token)elseoperand operand_stack pop(operand operand_stack pop(result do_math(tokenoperand operand operand_stack push(resultreturn operand_stack pop(def do_math(opop op )if op ="*"return op op elif op ="/"return op op elif op ="+"return op op elsereturn op op print(postfix_eval(' /')it is important to note that in both the postfix conversion and the postfix evaluation programs we assumed that there were no errors in the input expression using these programs as starting pointyou can easily see how error detection and reporting can be included we leave this as an exercise at the end of the self check convert the following expression to postfix /( modify the infix_to_postfix function so that it can convert the following expression ^( the stack abstract data type |
12,567 | figure queue of python data objects queues we now turn our attention to another linear data structure this one is called queue like stacksqueues are relatively simple and yet can be used to solve wide range of important problems what is queuea queue is an ordered collection of items where the addition of new items happens at one endcalled the "rear,and the removal of existing items occurs at the other endcommonly called the "front as an element enters the queue it starts at the rear and makes its way toward the frontwaiting until that time when it is the next element to be removed the most recently added item in the queue must wait at the end of the collection the item that has been in the collection the longest is at the front this ordering principle is sometimes called fifofirst-in first-out it is also known as "first-come first-served the simplest example of queue is the typical line that we all participate in from time to time we wait in line for moviewe wait in the check-out line at grocery storeand we wait in the cafeteria line (so that we can pop the tray stackwell-behaved linesor queuesare very restrictive in that they have only one way in and only one way out there is no jumping in the middle and no leaving before you have waited the necessary amount of time to get to the front figure shows simple queue of python data objects computer science also has common examples of queues our computer laboratory has computers networked with single printer when students want to printtheir print tasks "get in linewith all the other printing tasks that are waiting the first task in is the next to be completed if you are last in lineyou must wait for all the other tasks to print ahead of you we will explore this interesting example in more detail later in addition to printing queuesoperating systems use number of different queues to control processes within computer the scheduling of what gets done next is typically based on queuing algorithm that tries to execute programs as quickly as possible and serve as many users as it can alsoas we typesometimes keystrokes get ahead of the characters that appear on the screen this is due to the computer doing other work at that moment the keystrokes are being placed in queue-like buffer so that they can eventually be displayed on the screen in the proper order basic data structures |
12,568 | queue operation queue contents return value is_empty( enqueue( enqueue('dog' enqueue(trueq size( is_empty( enqueue( dequeue( dequeue( size([[ ['dog', [true,'dog', [true,'dog', [true,'dog', [ ,true,'dog', [ ,true,'dog'[ ,true[ ,truetrue false 'dog table example queue operations the queue abstract data type the queue abstract data type is defined by the following structure and operations queue is structuredas described aboveas an ordered collection of items which are added at one endcalled the "rear,and removed from the other endcalled the "front queues maintain fifo ordering property the queue operations are given below queue(creates new queue that is empty it needs no parameters and returns an empty queue enqueue(itemadds new item to the rear of the queue it needs the item and returns nothing dequeue(removes the front item from the queue it needs no parameters and returns the item the queue is modified is_empty(tests to see whether the queue is empty it needs no parameters and returns boolean value size(returns the number of items in the queue it needs no parameters and returns an integer as an exampleif we assume that is queue that has been created and is currently emptythen table shows the results of sequence of queue operations the queue contents are shown such that the front is on the right was the first item enqueued so it is the first item returned by dequeue implementing queue in python it is again appropriate to create new class for the implementation of the abstract data type queue as beforewe will use the power and simplicity of the list collection to build the internal representation of the queue we need to decide which end of the list to use as the rear and which to use as the front the implementation shown below assumes that the rear is at position in the list this allows us to use the insert function on lists to add new elements to the rear of the queue the pop operation queues |
12,569 | can be used to remove the front element (the last element of the listrecall that this also means that enqueue will be (nand dequeue will be ( completed implementation of queue adt class queuedef __init__(self)self items [def is_empty(self)return self items =[def enqueue(selfitem)self items insert( ,itemdef dequeue(self)return self items pop(def size(self)return len(self itemsself check suppose you have the following series of queue operationsq queue( enqueue('hello' enqueue('dog' enqueue( dequeue(what items are left in the queue 'hello''dog 'dog' 'hello' 'hello''dog' simulationhot potato one of the typical applications for showing queue in action is to simulate real situation that requires data to be managed in fifo manner to beginlet' consider the children' game hot potato in this game (see figure children line up in circle and pass an item from neighbour to neighbour as fast as they can at certain point in the gamethe action is stopped and the child who has the item (the potatois removed from the circle play continues until only one child is left basic data structures |
12,570 | figure six person game of hot potatothis game is modern-day equivalent of the famous josephus problem based on legend about the famous first-century historian flavius josephusthe story is told that in the jewish revolt against romejosephus and of his comrades held out against the romans in cave with defeat imminentthey decided that they would rather die than be slaves to the romans they arranged themselves in circle one man was designated as number oneand proceeding clockwise they killed every seventh man josephusaccording to the legendwas among other things an accomplished mathematician he instantly figured out where he ought to sit in order to be the last to go when the time cameinstead of killing himselfhe joined the roman side you can find many different versions of this story some count every third man and some allow the last man to escape on horse in any casethe idea is the same we will implement general simulation of hot potato our program will input list of names and constantcall it "numto be used for counting it will return the name of the last person remaining after repetitive counting by num what happens at that point is up to you to simulate the circlewe will use queue (see figure assume that the child holding the potato will be at the front of the queue upon passing the potatothe simulation will simply dequeue and then immediately enqueue that childputting her at the end of the line she will then wait until all the others have been at the front before it will be her turn again after num dequeue/enqueue operationsthe child at the front will be removed permanently and another cycle will begin this process will continue until only one name remains (the size of the queue is call to the hot_potato function using as the counting constant returns susan import queue as previously defined def hot_potato(name_listnum)sim_queue queue(for name in name_listsim_queue enqueue(name queues |
12,571 | figure queue implementation of hot potatowhile sim_queue size( for in range(num)sim_queue enqueue(sim_queue dequeue()sim_queue dequeue(return sim_queue dequeue(print(hot_potato(["bill""david""susan""jane""kent""brad"] )note that in this example the value of the counting constant is greater than the number of names in the list this is not problem since the queue acts like circle and counting continues back at the beginning until the value is reached alsonotice that the list is loaded into the queue such that the first name on the list will be at the front of the queue bill in this case is the first item in the list and therefore moves to the front of the queue variation of this implementationdescribed in the exercisesallows for random counter simulationprinting tasks more interesting simulation allows us to study the behavior of the printing queue described earlier in this section recall that as students send printing tasks to the shared printerthe tasks are placed in queue to be processed in first-come first-served manner many questions arise with this configuration the most important of these might be whether the printer is capable of handling certain amount of work if it cannotstudents will be waiting too long for printing and may miss their next class consider the following situation in computer science laboratory on any average day about students are working in the lab at any given hour these students typically print up to twice during that timeand the length of these tasks ranges from to pages the printer in the lab is oldercapable of processing pages per minute of draft quality the printer could be switched to give better qualitybut then it would produce only five pages per minute the slower printing speed could make students wait too long what page rate should be used basic data structures |
12,572 | figure computer science laboratory printing queuewe could decide by building simulation that models the laboratory we will need to construct representations for studentsprinting tasksand the printer (figure as students submit printing taskswe will add them to waiting lista queue of print tasks attached to the printer when the printer completes taskit will look at the queue to see if there are any remaining tasks to process of interest for us is the average amount of time students will wait for their papers to be printed this is equal to the average amount of time task waits in the queue to model this situation we need to use some probabilities for examplestudents may print paper from to pages in length if each length from to is equally likelythe actual length for print task can be simulated by using random number between and inclusive this means that there is equal chance of any length from to appearing if there are students in the lab and each prints twicethen there are print tasks per hour on average what is the chance that at any given seconda print task is going to be createdthe way to answer this is to consider the ratio of tasks to time twenty tasks per hour means that on average there will be one task every seconds hour minute task tasks hour minutes seconds seconds for every second we can simulate the chance that print task occurs by generating random number between and inclusive if the number is we say task has been created note that it is possible that many tasks could be created in row or we may wait quite while for task to appear that is the nature of simulation you want to simulate the real situation as closely as possible given that you know general parameters main simulation steps here is the main simulation create queue of print tasks each task will be given timestamp upon its arrival the queue is empty to start queues |
12,573 | for each second (current_second)does new print task get createdif soadd it to the queue with the current_second as the timestamp if the printer is not busy and if task is waitingremove the next task from the print queue and assign it to the printer subtract the timestamp from the current_second to compute the waiting time for that task append the waiting time for that task to list for later processing based on the number of pages in the print taskfigure out how much time will be required the printer now does one second of printing if necessary it also subtracts one second from the time required for that task if the task has been completedin other words the time required has reached zerothe printer is no longer busy after the simulation is completecompute the average waiting time from the list of waiting times generated python implementation to design this simulation we will create classes for the three real-world objects described aboveprintertaskand printqueue the printer class will need to track whether it has current task if it doesthen it is busy and the amount of time needed can be computed from the number of pages in the task the constructor will also allow the pages-per-minute setting to be initialized the tick method decrements the internal timer and sets the printer to idle if the task is completed class printerdef __init__(selfppm)self page_rate ppm self current_task none self time_remaining def tick(self)if self current_task !noneself time_remaining self time_remaining if self time_remaining < self current_task none def busy(self)if self current_task !nonereturn true elsereturn false basic data structures |
12,574 | def start_next(self,new_task)self current_task new_task self time_remaining new_task get_pages( self page_rate the task class will represent single printing task when the task is createda random number generator will provide length from to pages we have chosen to use the randrange function from the random module import random random randrange( random randrange( each task will also need to keep timestamp to be used for computing waiting time this timestamp will represent the time that the task was created and placed in the printer queue the wait_time method can then be used to retrieve the amount of time spent in the queue before printing begins import random class taskdef __init__(selftime)self timestamp time self pages random randrange( def get_stamp(self)return self timestamp def get_pages(self)return self pages def wait_time(selfcurrent_time)return current_time self timestamp the main simulation implements the algorithm described above the print_queue object is an instance of our existing queue adt boolean helper functionnew_print_taskdecides whether new printing task has been created we have again chosen to use the randrange function from the random module to return random integer between and print tasks arrive once every seconds by arbitrarily choosing from the range of random integerswe can simulate this random event the simulation function allows us to set the total time and the pages per minute for the printer import queue as previously defined import printer as previously defined queues |
12,575 | import task as previously defined import random def simulation(num_secondspages_per_minute)lab_printer printer(pages_per_minuteprint_queue queue(waiting_times [for current_second in range(num_seconds)if new_print_task()task task(current_secondprint_queue enqueue(taskif (not lab_printer busy()and (not print_queue is_empty())next_task print_queue dequeue(waiting_times append(next_task wait_time(current_second)lab_printer start_next(next_tasklab_printer tick(average_wait sum(waiting_timeslen(waiting_timesprint("average wait % secs % tasks remaining %(average_waitprint_queue size())def new_print_task()num random randrange( if num = return true elsereturn false for in range( )simulation( when we run the simulationwe should not be concerned that the results are different each time this is due to the probabilistic nature of the random numbers we are interested in the trends that may be occurring as the parameters to the simulation are adjusted here are some results firstwe will run the simulation for period of minutes ( secondsusing page rate of five pages per minute in additionwe will run independent trials remember that because the simulation works with random numbers each run will return different results for in range( )simulation( average wait secs tasks remaining average wait secs tasks remaining basic data structures |
12,576 | average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining after running our trials we can see that the mean average wait time is seconds you can also see that there is large variation in the average weight time with minimum average of seconds and maximum of seconds you may also notice that in only two of the cases were all the tasks completed nowwe will adjust the page rate to pages per minuteand run the trials againwith faster page rate our hope would be that more tasks would be completed in the one hour time frame for in range( )simulation( average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining the code to run the simulation is as followsimport queue as previously defined import random completed program for the printer simulation class printerdef __init__(selfppm)self page_rate ppm self current_task none self time_remaining def tick(self)if self current_task !noneself time_remaining self time_remaining if self time_remaining < queues |
12,577 | self current_task none def busy(self)if self current_task !nonereturn true elsereturn false def start_next(selfnew_task)self current_task new_task self time_remaining new_task get_pages( /self page_rate class taskdef __init__(selftime)self timestamp time self pages random randrange( def get_stamp(self)return self timestamp def get_pages(self)return self pages def wait_time(selfcurrent_time)return current_time self timestamp def simulation(num_secondspages_per_minute)lab_printer printer(pages_per_minuteprint_queue queue(waiting_times [for current_second in range(num_seconds)if new_print_task()task task(current_secondprint_queue enqueue(taskif (not lab_printer busy()and (not print_queue is_empty())next_task print_queue dequeue(waiting_times append(next_task wait_time(current_second)lab_printer startnext(next_tasklab_printer tick(average_wait sum(waiting_timeslen(waiting_timesprint("average wait % secs % tasks remaining %(average_waitprint_queue size())def new_print_task() basic data structures |
12,578 | num random randrange( if num = return true elsereturn false for in range( )simulation( discussion we were trying to answer question about whether the current printer could handle the task load if it were set to print with better quality but slower page rate the approach we took was to write simulation that modeled the printing tasks as random events of various lengths and arrival times the output above shows that with pages per minute printingthe average waiting time varied from low of seconds to high of seconds (about minuteswith faster printing ratethe low value was second with high of only in additionin out of runs at pages per minute there were print tasks still waiting in the queue at the end of the hour thereforewe are perhaps persuaded that slowing the printer down to get better quality may not be good idea students cannot afford to wait that long for their papersespecially when they need to be getting on to their next class six-minute wait would simply be too long this type of simulation analysis allows us to answer many questionscommonly known as "what ifquestions all we need to do is vary the parameters used by the simulation and we can simulate any number of interesting behaviors for examplewhat if enrolment goes up and the average number of students increases by what if it is saturday and students are not needing to get to classcan they afford to waitwhat if the size of the average print task decreases since python is such powerful language and programs tend to be much shorterthese questions could all be answered by modifying the above simulation howeverit is important to remember that the simulation is only as good as the assumptions that are used to build it real data about the number of print tasks per hour and the number of students per hour was necessary to construct robust simulation self check how would you modify the printer simulation to reflect larger number of studentssuppose that the number of students was doubled you make need to make some reasonable assumptions about how this simulation was put together but what would you changemodify the code also suppose that the length of the average print task was cut in half change the code to reflect that change finally how would you parameterize the number of studentsrather than changing the code we would like to make the number of students parameter of the simulation queues |
12,579 | figure deque of python data objects queue deques we will conclude this introduction to basic data structures by looking at another variation on the theme of linear collections howeverunlike stack and queuethe deque (pronounced "deck"has very few restrictions alsobe careful that you do not confuse the spelling of "dequewith the queue removal operation "dequeue what is dequea dequealso known as double-ended queueis an ordered collection of items similar to the queue it has two endsa front and rearand the items remain positioned in the collection what makes deque different is the unrestrictive nature of adding and removing items new items can be added at either the front or the rear likewiseexisting items can be removed from either end in sensethis hybrid linear structure provides all the capabilities of stacks and queues in single data structure figure shows deque of python data objects it is important to note that even though the deque can assume many of the characteristics of stacks and queuesit does not require the lifo and fifo orderings that are enforced by those data structures it is up to you to make consistent use of the addition and removal operations the deque abstract data type the deque abstract data type is defined by the following structure and operations deque is structuredas described aboveas an ordered collection of items where items are added and removed from either endeither front or rear the deque operations are given below deque(creates new deque that is empty it needs no parameters and returns an empty deque add_front(itemadds new item to the front of the deque it needs the item and returns nothing basic data structures |
12,580 | deque operation deque contents return value is_empty( add_rear( add_rear('dog' add_front('cat' add_front(trued size( is_empty( add_rear( remove_rear( remove_front([[ ['dog', ,['dog', ,'cat'['dog', ,'cat',true['dog', ,'cat',true['dog', ,'cat',true[ ,'dog', ,'cat',true['dog', ,'cat',true['dog', ,'cat'true false true table examples of deque operations add_rear(itemadds new item to the rear of the deque it needs the item and returns nothing remove_front(removes the front item from the deque it needs no parameters and returns the item the deque is modified remove_rear(removes the rear item from the deque it needs no parameters and returns the item the deque is modified is_empty(tests to see whether the deque is empty it needs no parameters and returns boolean value size(returns the number of items in the deque it needs no parameters and returns an integer as an exampleif we assume that is deque that has been created and is currently emptythen table shows the results of sequence of deque operations note that the contents in front are listed on the right it is very important to keep track of the front and the rear as you move items in and out of the collection as things can get bit confusing implementing deque in python as we have done in previous sectionswe will create new class for the implementation of the abstract data type deque againthe python list will provide very nice set of methods upon which to build the details of the deque our implementation will assume that the rear of the deque is at position in the list completed implementation of deque adt class dequedef __init__(self)self items [def is_empty(self)return self items =[def add_front(selfitem) deques |
12,581 | self items append(itemdef add_rear(selfitem)self items insert( ,itemdef remove_front(self)return self items pop(def remove_rear(self)return self items pop( def size(self)return len(self itemsin remove_front we use the pop method to remove the last element from the list howeverin remove_rearthe pop( method must remove the first element of the list likewisewe need to use the insert method in add_rear since the append method assumes the addition of new element to the end of the list you can see many similarities to python code already described for stacks and queues you are also likely to observe that in this implementation adding and removing items from the front is ( whereas adding and removing from the rear is (nthis is to be expected given the common operations that appear for adding and removing items againthe important thing is to be certain that we know where the front and rear are assigned in the implementation palindrome checker an interesting problem that can be easily solved using the deque data structure is the classic palindrome problem palindrome is string that reads the same forward and backwardfor exampleradartootand madam we would like to construct an algorithm to input string of characters and check whether it is palindrome the solution to this problem will use deque to store the characters of the string we will process the string from left to right and add each character to the rear of the deque at this pointthe deque will be acting very much like an ordinary queue howeverwe can now make use of the dual functionality of the deque the front of the deque will hold the first character of the string and the rear of the deque will hold the last character (see figure since we can remove both of them directlywe can compare them and continue only if they match if we can keep matching first and the last itemswe will eventually either run out of characters or be left with deque of size depending on whether the length of the original string was even or odd in either casethe string must be palindrome import deque as previously defined def pal_checker(a_string)char_deque deque(for ch in a_string basic data structures |
12,582 | figure dequechar_deque add_rear(chstill_equal true while char_deque size( and still_equalfirst char_deque remove_front(last char_deque remove_rear(if first !laststill_equal false return still_equal print(pal_checker("lsdkjfskf")print(pal_checker("radar") lists throughout the discussion of basic data structureswe have used python lists to implement the abstract data types presented the list is powerfulyet simplecollection mechanism that provides the programmer with wide variety of operations howevernot all programming languages include list collection in these casesthe notion of list must be implemented by the programmer list is collection of items where each item holds relative position with respect to the others more specificallywe will refer to this type of list as an unordered list we can consider the list as having first itema second itema third itemand so on we can also refer to the beginning of the list (the first itemor the end of the list (the last itemfor simplicity we will assume that lists cannot contain duplicate items for examplethe collection of integers and might represent simple unordered list of exam scores note that we have written them as comma-delimited values lists |
12,583 | common way of showing the list structure of coursepython would show this list as [ the unordered list abstract data type the structure of an unordered listas described aboveis collection of items where each item holds relative position with respect to the others some possible unordered list operations are given below list(creates new list that is empty it needs no parameters and returns an empty list add(itemadds new item to the list it needs the item and returns nothing assume the item is not already in the list remove(itemremoves the item from the list it needs the item and modifies the list assume the item is present in the list search(itemsearches for the item in the list it needs the item and returns boolean value is_empty(tests to see whether the list is empty it needs no parameters and returns boolean value size(returns the number of items in the list it needs no parameters and returns an integer append(itemadds new item to the end of the list making it the last item in the collection it needs the item and returns nothing assume the item is not already in the list index(itemreturns the position of item in the list it needs the item and returns the index assume the item is in the list insert(pos,itemadds new item to the list at position pos it needs the item and returns nothing assume the item is not already in the list and there are enough existing items to have position pos pop(removes and returns the last item in the list it needs nothing and returns an item assume the list has at least one item pop(posremoves and returns the item at position pos it needs the position and returns the item assume the item is in the list implementing an unordered listlinked lists in order to implement an unordered listwe will construct what is commonly known as linked list recall that we need to be sure that we can maintain the relative positioning of the items howeverthere is no requirement that we maintain that positioning in contiguous memory for exampleconsider the collection of items shown in figure it appears that these values have been placed randomly if we can maintain some explicit information in each itemnamely basic data structures |
12,584 | figure items not constrained in their physical placement figure relative positions maintained by explicit links the location of the next item (see figure then the relative position of each item can be expressed by simply following the link from one item to the next it is important to note that the location of the first item of the list must be explicitly specified once we know where the first item isthe first item can tell us where the second isand so on the external reference is often referred to as the head of the list similarlythe last item needs to know that there is no next item the node class the basic building block for the linked list implementation is the node each node object must hold at least two pieces of information firstthe node must contain the list item itself we will call this the data field of the node in additioneach node must hold reference to the next node to construct nodeyou need to supply the initial data value for the node evaluating the assignment statement below will yield node object containing the value (see figure you should note that we will typically represent node object as shown in figure the node class also includes the usual methods to access and modify the data and the next reference class nodedef __init__(selfinit_data)self data init_data self next none def get_data(self)return self data implementing an unordered listlinked lists |
12,585 | figure node object contains the item and reference to the next node figure typical representation for node def get_next(self)return self next def set_data(selfnew_data)self data newdata def set_next(selfnew_next)self next new_next we create node objects in the usual way temp node( temp get_data( the special python reference value none will play an important role in the node class and later in the linked list itself reference to none will denote the fact that there is no next node note in the constructor that node is initially created with next set to none since this is sometimes referred to as "grounding the node,we will use the standard ground symbol to denote reference that is referring to none it is always good idea to explicitly assign none to your initial next reference values the unordered list class as we suggested abovethe unordered list will be built from collection of nodeseach linked to the next by explicit references as long as we know where to find the first node (containing the first item)each item after that can be found by successively following the next links with this in mindthe unorderedlist class must maintain reference to the first node the following code shows the constructor note that each list object will maintain single reference to the head of the list class unorderedlist basic data structures |
12,586 | figure an empty list figure linked list of integers def __init__(self)self head none initially when we construct listthere are no items the assignment statement mylist unorderedlist(creates the linked list representation shown in figure as we discussed in the node classthe special reference none will again be used to state that the head of the list does not refer to anything eventuallythe example list given earlier will be represented by linked list as shown in figure the head of the list refers to the first node which contains the first item of the list in turnthat node holds reference to the next node (the next itemand so on it is very important to note that the list class itself does not contain any node objects instead it contains single reference to only the first node in the linked structure the is_empty method simply checks to see if the head of the list is reference to none the result of the boolean expression self head==none will only be true if there are no nodes in the linked list since new list is emptythe constructor and the check for empty must be consistent with one another this shows the advantage to using the reference none to denote the "endof the linked structure in pythonnone can be compared to any reference two references are equal if they both refer to the same object we will use this often in our remaining methods def is_empty(self)return self head =none sohow do we get items into our listwe need to implement the add method howeverbefore we can do thatwe need to address the important question of where in the linked list to place the new item since this list is unorderedthe specific location of the new item with respect to the other items already in the list is not important the new item can go anywhere with that in mindit makes sense to place the new item in the easiest location possible implementing an unordered listlinked lists |
12,587 | figure adding new node is two-step process recall that the linked list structure provides us with only one entry pointthe head of the list all of the other nodes can only be reached by accessing the first node and then following next links this means that the easiest place to add the new node is right at the heador beginningof the list in other wordswe will make the new item the first item of the list and the existing items will need to be linked to this new first item so that they follow the linked list shown in figure was built by calling the add method number of times mylist add( mylist add( mylist add( mylist add( mylist add( mylist add( note that since is the first item added to the listit will eventually be the last node on the linked list as every other item is added ahead of it alsosince is the last item addedit will become the data value in the first node of the linked list the add method is shown below each item of the list must reside in node object line creates new node and places the item as its data now we must complete the process by linking the new node into the existing structure this requires two steps as shown in figure step (line changes the next reference of the new node to refer to the old first node of the list now that the rest of the list has been properly attached to the new nodewe can modify the head of the list to refer to the new node the assignment statement in line sets the head of the list the order of the two steps described above is very important what happens if the order of line and line is reversedif the modification of the head of the list happens firstthe result can be seen in figure since the head was the only external reference to the list nodesall of the original nodes are lost and can no longer be accessed def add(selfitem)temp node(itemtemp set_next(self headself head temp the next methods that we will implement-sizesearchand remove-are all based on technique known as linked list traversal traversal refers to the process of systematically visiting each basic data structures |
12,588 | figure result of reversing the order of the two steps figure traversing the linked list from the head to the end node to do this we use an external reference that starts at the first node in the list as we visit each nodewe move the reference to the next node by "traversingthe next reference to implement the size methodwe need to traverse the linked list and keep count of the number of nodes that occurred below we show the python code for counting the number of nodes in the list the external reference is called current and is initialized to the head of the list in line at the start of the process we have not seen any nodes so the count is set to lines - actually implement the traversal as long as the current reference has not seen the end of the list (none)we move current along to the next node via the assignment statement in line againthe ability to compare reference to none is very useful every time current moves to new nodewe add to count finallycount gets returned after the iteration stops figure shows this process as it proceeds down the list def size(self)current self head count while current !nonecount count current current get_next(return count searching for value in linked list implementation of an unordered list also uses the traversal technique as we visit each node in the linked list we will ask whether the data stored there matches the item we are looking for in this casehoweverwe may not have to traverse all the way to the end of the list in factif we do get to the end of the listthat means that the item we are looking for must not be present alsoif we do find the itemthere is no need to continue implementing an unordered listlinked lists |
12,589 | figure successful search for the value the code below shows the implementation for the search method as in the size methodthe traversal is initialized to start at the head of the list (line we also use boolean variable called found to remember whether we have located the item we are searching for since we have not found the item at the start of the traversalfound can be set to false (line the iteration in line takes into account both conditions discussed above as long as there are more nodes to visit and we have not found the item we are looking forwe continue to check the next node the question in line asks whether the data item is present in the current node if sofound can be set to true def search(self,item)current self head found false while current !none and not foundif current get_data(=itemfound true elsecurrent current get_next(return found as an exampleconsider invoking the search method looking for the item mylist search( true since is in the listthe traversal process needs to move only to the node containing at that pointthe variable found is set to true and the while condition will failleading to the return value seen above this process can be seen in figure he remove method requires two logical steps firstwe need to traverse the list looking for the item we want to remove once we find the item (recall that we assume it is present)we must remove it the first step is very similar to search starting with an external reference set to the head of the listwe traverse the links until we discover the item we are looking for since we assume that item is presentwe know that the iteration will stop before current gets to none this means that we can simply use the boolean found in the condition when found becomes truecurrent will be reference to the node containing the item to be removed but how do we remove itone possibility would be to replace the value of the basic data structures |
12,590 | item with some marker that suggests that the item is no longer present the problem with this approach is the number of nodes will no longer match the number of items it would be much better to remove the item by removing the entire node in order to remove the node containing the itemwe need to modify the link in the previous node so that it refers to the node that comes after current unfortunatelythere is no way to go backward in the linked list since current refers to the node ahead of the node where we would like to make the changeit is too late to make the necessary modification the solution to this dilemma is to use two external references as we traverse down the linked list current will behave just as it did beforemarking the current location of the traverse the new referencewhich we will call previouswill always travel one node behind current that waywhen current stops at the node to be removedprevious will be referring to the proper place in the linked list for the modification the code below shows the complete remove method lines - assign initial values to the two references note that current starts out at the list head as in the other traversal examples previoushoweveris assumed to always travel one node behind current for this reasonprevious starts out with value of none since there is no node before the head (see figure the boolean variable found will again be used to control the iteration in lines - we ask whether the item stored in the current node is the item we wish to remove if sofound can be set to true if we do not find the itemprevious and current must both be moved one node ahead againthe order of these two statements is crucial previous must first be moved one node ahead to the location of current at that pointcurrent can be moved this process is often referred to as "inch-wormingas previous must catch up to current before current moves ahead figure shows the movement of previous and current as they progress down the list looking for the node containing the value def remove(selfitem)current self head previous none found false while not foundif current get_data(=itemfound true elseprevious current current current get_next( if previous =noneself head current get_next(elseprevious set_next(current get_next()once the searching step of the remove has been completedwe need to remove the node from the linked list figure shows the link that must be modified howeverthere is special case that needs to be addressed if the item to be removed happens to be the first item in the listthen current will reference the first node in the linked list this also means that previous will be none we said earlier that previous would be referring to the node whose next reference implementing an unordered listlinked lists |
12,591 | figure initial values for the previous and current references figure previous and current move down the list basic data structures |
12,592 | figure removing an item from the middle of the list figure removing the first node from the list needs to be modified in order to complete the remove in this caseit is not previous but rather the head of the list that needs to be changed (see figure line allows us to check whether we are dealing with the special case described above if previous did not moveit will still have the value none when the boolean found becomes true in that case (line the head of the list is modified to refer to the node after the current nodein effect removing the first node from the linked list howeverif previous is not nonethe node to be removed is somewhere down the linked list structure in this case the previous reference is providing us with the node whose next reference must be changed line uses the set_next method from previous to accomplish the removal note that in both cases the destination of the reference change is current get_next(one question that often arises is whether the two cases shown here will also handle the situation where the item to be removed is in the last node of the linked list we leave that for you to consider the remaining methods appendinsertindexand pop are left as exercises remember that each of these must take into account whether the change is taking place at the head of the list or someplace else alsoinsertindexand pop require that we name the positions of the list we will assume that position names are integers starting with self check implement the append method for unorderedlist what is the time complexity of the method you createdit was most likely (nif you add an instance variable to the unorderedlist class you can create an append method that is ( modify your append to be ( be carefulto really do this correctly you will need to consider couple of special cases that may require you to make modification to the add method as well implementing an unordered listlinked lists |
12,593 | figure an ordered linked list the ordered list abstract data type we will now consider type of list known as an ordered list for exampleif the list of integers shown above were an ordered list (ascending order)then it could be written as and since is the smallest itemit occupies the first position in the list likewisesince is the largestit occupies the last position the structure of an ordered list is collection of items where each item holds relative position that is based upon some underlying characteristic of the item the ordering is typically either ascending or descending and we assume that list items have meaningful comparison operation that is already defined many of the ordered list operations are the same as those of the unordered list orderedlist(creates new ordered list that is empty it needs no parameters and returns an empty list add(itemadds new item to the list making sure that the order is preserved it needs the item and returns nothing assume the item is not already in the list remove(itemremoves the item from the list it needs the item and modifies the list assume the item is present in the list search(itemsearches for the item in the list it needs the item and returns boolean value is_empty(tests to see whether the list is empty it needs no parameters and returns boolean value size(returns the number of items in the list it needs no parameters and returns an integer index(itemreturns the position of item in the list it needs the item and returns the index assume the item is in the list pop(removes and returns the last item in the list it needs nothing and returns an item assume the list has at least one item pop(posremoves and returns the item at position pos it needs the position and returns the item assume the item is in the list implementing an ordered list in order to implement the ordered listwe must remember that the relative positions of the items are based on some underlying characteristic the ordered list of integers given above ( and can be represented by linked structure as shown in figure againthe node and link structure is ideal for representing the relative positioning of the items basic data structures |
12,594 | figure searching an ordered linked list to implement the orderedlist classwe will use the same technique as seen previously with unordered lists once againan empty list will be denoted by head reference to none class orderedlistdef __init__(self)self head none as we consider the operations for the ordered listwe should note that the is_empty and size methods can be implemented the same as with unordered lists since they deal only with the number of nodes in the list without regard to the actual item values likewisethe remove method will work just fine since we still need to find the item and then link around the node to remove it the two remaining methodssearch and addwill require some modification the search of an unordered linked list required that we traverse the nodes one at time until we either find the item we are looking for or run out of nodes (noneit turns out that the same approach would actually work with the ordered list and in fact in the case where we find the item it is exactly what we need howeverin the case where the item is not in the listwe can take advantage of the ordering to stop the search as soon as possible for examplefigure shows the ordered linked list as search is looking for the value as we traversestarting at the head of the listwe first compare against since is not the item we are looking forwe move to the next nodein this case againthis is not what we wantso we move on to and then on to nowat this pointsomething is different since is not the item we are looking forour former strategy would be to move forward howeverdue to the fact that this is an ordered listthat will not be necessary once the value in the node becomes greater than the item we are searching forthe search can stop and return false there is no way the item could exist further out in the linked list the following code shows the complete search method it is easy to incorporate the new condition discussed above by adding another boolean variablestopand initializing it to false (line while stop is false (not stopwe can continue to look forward in the list (line if any node is ever discovered that contains data greater than the item we are looking forwe will set stop to true (lines - the remaining lines are identical to the unordered list search def search(selfitem)current self head found false stop false while current !none and not found and not stop the ordered list abstract data type |
12,595 | figure adding an item to an ordered linked list if current get_data(=itemfound true elseif current get_data(itemstop true elsecurrent current get_next( return found the most significant method modification will take place in add recall that for unordered liststhe add method could simply place new node at the head of the list it was the easiest point of access unfortunatelythis will no longer work with ordered lists it is now necessary that we discover the specific place where new item belongs in the existing ordered list assume we have the ordered list consisting of and and we want to add the value the add method must decide that the new item belongs between and figure shows the setup that we need as we explained earlierwe need to traverse the linked list looking for the place where the new node will be added we know we have found that place when either we run out of nodes (current becomes noneor the value of the current node becomes greater than the item we wish to add in our exampleseeing the value causes us to stop as we saw with unordered listsit is necessary to have an additional referenceagain called previoussince current will not provide access to the node that must be modified the below code shows the complete add method lines - set up the two external references and lines - again allow previous to follow one node behind current every time through the iteration the condition (line allows the iteration to continue as long as there are more nodes and the value in the current node is not larger than the item in either casewhen the iteration failswe have found the location for the new node the remainder of the method completes the two-step process shown in figure once new node has been created for the itemthe only remaining question is whether the new node will be added at the beginning of the linked list or some place in the middle againprevious =none (line can be used to provide the answer def add(selfitem)current self head previous none stop false basic data structures |
12,596 | while current !none and not stopif current get_data(itemstop true elseprevious current current current get_next( temp node(itemif previous =nonetemp set_next(self headself head temp elsetemp set_next(currentprevious set_next(tempanalysis of linked lists to analyze the complexity of the linked list operationswe need to consider whether they require traversal consider linked list that has nodes the is_empty method is ( since it requires one step to check the head reference for none sizeon the other handwill always require steps since there is no way to know how many nodes are in the linked list without traversing from head to end thereforelength is (nadding an item to an unordered list will always be ( since we simply place the new node at the head of the linked list howeversearch and removeas well as add for an ordered listall require the traversal process although on average they may need to traverse only half of the nodesthese methods are all (nsince in the worst case each will process every node in the list you may also have noticed that the performance of this implementation differs from the actual performance given earlier for python lists this suggests that linked lists are not the way python lists are implemented the actual implementation of python list is based on the notion of an array we discuss this in more detail in another summary linear data structures maintain their data in an ordered fashion stacks are simple data structures that maintain lifolast-in first-outordering the fundamental operations for stack are pushpopand is_empty queues are simple data structures that maintain fifofirst-in first-outordering the fundamental operations for queue are enqueuedequeueand is_empty prefixinfixand postfix are all ways to write expressions stacks are very useful for designing algorithms to evaluate and translate expressions stacks can provide reversal characteristic summary |
12,597 | queues can assist in the construction of timing simulations simulations use random number generators to create real-life situation and allow us to answer "what iftypes of questions deques are data structures that allow hybrid behavior like that of stacks and queues the fundamental operations for deque are add_frontadd_rearremove_frontremove_rearand is_empty lists are collections of items where each item holds relative position linked list implementation maintains logical order without requiring physical storage requirements modification to the head of the linked list is special case key terms balanced parentheses first-in first-out (fifoinfix linked list node precedence simulation data field fully parenthesized last-in first-out (lifolinked list traversal palindrome prefix stack deque head linear data structure list postfix queue discussion questions convert the following values to binary using "divide by show the stack of remainders convert the following infix expressions to prefix (use full parentheses)( ( ( (( ( ) * * * + + convert the above infix expressions to postfix (use full parentheses convert the above infix expressions to postfix using the direct conversion algorithm show the stack as the conversion takes place evaluate the following postfix expressions show the stack as each operand and operator is processed basic data structures |
12,598 | the alternative implementation of the queue adt is to use list such that the rear of the queue is at the end of the list what would this mean for big- performance what is the result of carrying out both steps of the linked list add method in reverse orderwhat kind of reference resultswhat types of problems may result explain how the linked list remove method works when the item to be removed is in the last node explain how the remove method works when the item is in the only node in the linked list programming exercises modify the infix-to-postfix algorithm so that it can handle errors modify the postfix evaluation algorithm so that it can handle errors implement direct infix evaluator that combines the functionality of infix-to-postfix conversion and the postfix evaluation algorithm your evaluator should process infix tokens from left to right and use two stacksone for operators and one for operandsto perform the evaluation turn your direct infix evaluator from the previous problem into calculator implement the queue adtusing list such that the rear of the queue is at the end of the list design and implement an experiment to do benchmark comparisons of the two queue implementations what can you learn from such an experiment it is possible to implement queue such that both enqueue and dequeue have ( performance on average in this case it means that most of the time enqueue and dequeue will be ( except in one particular circumstance where dequeue will be ( consider real life situation formulate question and then design simulation that can help to answer it possible situations includecars lined up at car wash customers at grocery store check-out airplanes taking off and landing on runway bank teller be sure to state any assumptions that you make and provide any probabilistic data that must be considered as part of the scenario programming exercises |
12,599 | modify the hot potato simulation to allow for randomly chosen counting value so that each pass is not predictable from the previous one implement radix sorting machine radix sort for base integers is mechanical sorting technique that utilizes collection of binsone main bin and digit bins each bin acts like queue and maintains its values in the order that they arrive the algorithm begins by placing each number in the main bin then it considers each value digit by digit the first value is removed and placed in digit bin corresponding to the digit being considered for exampleif the ones digit is being considered is placed in digit bin and is placed in digit bin once all the values are placed in the corresponding digit binsthe values are collected from bin to bin and placed back in the main bin the process continues with the tens digitthe hundredsand so on after the last digit is processedthe main bin contains the values in order another example of the parentheses matching problem comes from hypertext markup language (htmlin htmltags exist in both opening and closing forms and must be balanced to properly describe web document this very simple html documentexample helloworld is intended only to show the matching and nesting structure for tags in the language write program that can check an html document for proper opening and closing tags to implement the length methodwe counted the number of nodes in the list an alternative strategy would be to store the number of nodes in the list as an additional piece of data in the head of the list modify the unorderedlist class to include this information and rewrite the length method implement the remove method so that it works correctly in the case where the item is not in the list modify the list classes to allow duplicates which methods will be impacted by this change implement the __str__ method in the unorderedlist class what would be good string representation for list implement __str__ method so that lists are displayed the python way (with square brackets basic data structures |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.