id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
13,500 | stringslike all sequence typessupport indexing and slicing we can retrieve any character from string by using its index [iwe can retrieve slice of string by using [ : ]where and are the start and end points of the slice we can return an extended slice by using strideas in the followings[ : :stridethe following code should make this clearthe first two examples are pretty straightforwardreturning the character located at index and the first seven characters of the stringrespectively notice that indexing begins at in the third examplewe are using stride of this results in every second character being returned in the final examplewe omit the end index and the slice returns every second character in the entire string you can use any expressionvariableor operator as an index as long as the value is an integerfor exampleanother common operation is traversing through string with loopfor example |
13,501 | given that strings are immutablea common question that arises is how we perform operations such inserting values rather than changing stringwe need to think of ways to build new string objects for the results we need for exampleif we wanted to insert word into our greetingwe could assign variable to the followingas this code showswe use the slice operator to split the string at index position and use to concatenate python never interprets the contents of string as number if we need to perform mathematical operations on stringwe need to first convert them to numeric typefor examplelists lists are probably the most used built-in data structures in python because they can be composed of any number of other data types they are simple representation of arbitrary objects like stringsthey are indexed by integers starting with zero the following table contains the most commonly used list methods and their descriptionsmethod description list(sreturns list of the sequence append(xappends element to the end of extend(xappends the list to count(xcounts the occurrence of in index( [start][stop]returns the smallest indexiwhere [ == can include optional start and stop index for the search |
13,502 | insert( ,einserts at index pop(ireturns the element and removes it from the list remove(xremoves from reverse(reverses the order of sort(key ,[reverse]sorts with optional key and reverse when we are working with listsand other container objectsit is important to understand the internal mechanism that python uses to copy them python creates real copies only if it has to when we assign the value of variable to another variableboth of these variables point to the same memory location new slot in memory will only be allocated if one of the variables changes this has important consequences for mutable compound objects such as lists consider the following codehereboth the list and list variables point to the same slot in memory when we change the variable to we are changing the same variable that list is pointing to an important feature of list' is that they can contain nested structuresthat isother listsfor examplewe can access the lists values using the bracket operators and since lists are mutablethey are copied in place the following example demonstrates how we can use this to update elementsfor examplehere we are raising the price of flour by percent |
13,503 | common and very intuitive way to create lists from expressions is using list comprehensions this allows us to create list by writing an expression directly into the listfor examplelist comprehensions can be quite flexiblefor exampleconsider the following code it essentially shows two different ways to performs function compositionwhere we apply one function ( to another ( the following code prints out two lists representing the function composition of and calculated first using for loop and then using list comprehensiondef ( )return * def ( )return * lst [for in range( )lst append( ( ( ))print(lstprint([ (xfor in range( if in [ (jfor in range( )]]the first line of output is from the for loop construct the second is from the list comprehension expression |
13,504 | list comprehensions can also be used to replicate the action of nested loops in more compact form for examplewe multiply each of the elements contained within list with each otherwe can also use list comprehensions with other objects such as stringsto build more complex structures for examplethe following code creates list of words and their letter countas we will seelists form the foundation of many of the data structures we will look at their versatilityease of creationand use enables them to build more specialized and complex data structures functions as first class objects in pythonit is not only data types that are treated as objects both functions and classes are what are known as first class objectsallowing them to be manipulated in the same ways as built-in data types by definitionfirst class objects arecreated at runtime assigned as variable or in data structure passed as an argument to function returned as the result of function in pythonthe term first class object is bit of misnomer since it implies some sort of hierarchywhereas all python objects are essentially first class |
13,505 | to have look at how this workslet' define simple functiondef greeting(language)if language='eng'return 'hello worldif language ='frreturn 'bonjour le mondeelsereturn 'language not supportedsince user-defined functions are objectswe can do things such as include them in other objectssuch as listsfunctions can also be used as arguments for other functions for examplewe can define the following functionherecallf(takes function as an argumentsets language variable to 'eng'and then calls the function with the language variable as its argument we could see how this would be useful iffor examplewe wanted to produce program that returns specific sentences in variety of languagesperhaps for some sort of natural language application here we have central place to set the language as well as our greeting functionwe could create similar functions that return different sentences by having one point where we set the languagethe rest of the program logic does not have to worry about this if we want to change the languagewe simply change the language variable and we can keep everything else the same |
13,506 | higher order functions functions that take other functions as argumentsor that return functionsare called higher order functions python contains two built-in higher order functionsfilter(and map(note that in earlier versions of pythonthese functions returned listsin python they return an iteratormaking them much more efficient the map(function provides an easy way to transform each item into an iterable object for examplehere is an efficientcompact way to perform an operation on sequence note the use of the lambda anonymous functionsimilarlywe can use the filter built-in function to filter items in listnote that both map and filter perform the identical function as to what can be achieved by list comprehensions there does not seem to be great deal of difference in the performance characteristics apart from slight performance advantage when using the in built functions map and filter without the lambda operatorcompared to list comprehensions despite thismost style guides recommend the use of list comprehensions over built-in functionspossibly because they tend to be easier to read creating our own higher order functions is one of the hallmarks of functional programming style practical example of how higher order functions can be useful is demonstrated by the following here we are passing the len function as the key to the sort function this waywe can sort list of words by length |
13,507 | here is another example for case-insensitive sortingnote the difference between the list sort(method and the sorted built-in function list sort() method of the list objectsorts the existing instance of list without copying it this method changes the target object and returns none it is an important convention in python that functions or methods that change the object return none to make it clear that no new object was created and that the object itself was changed on the other handthe sorted built-in function returns new list it actually accepts any iterable object as an argumentbut it will always return list both list sort and sorted take two optional keyword arguments as key simple way to sort more complex structures is to use the index of the element to sort using the lambda operatorfor examplehere we have sorted the items by price |
13,508 | recursive functions recursion is one of the most fundamental concepts of computer science in pythonwe can implement recursive function simply by calling it within its own function body to stop recursive function turning into an infinite loopwe need at least one argument that tests for terminating case to end the recursion this is sometimes called the base case it should be pointed out that recursion is different from iteration although both involve repetitioniteration loops through sequence of operationswhereas recursion repeatedly calls function both need selection statement to end technicallyrecursion is special case of iteration known as tail iterationand it is usually always possible to convert an iterative function to recursive function and vice versa the interesting thing about recursive functions is that they are able to describe an infinite object within finite statement the following code should demonstrate the difference between recursion and iteration both these functions simply print out numbers between low and highthe first one using iteration and the second using recursionnoticeitertestthe iteration examplewe use while statement to test for the conditionthen call the print methodand finally increment the low value the recursive example tests for the conditionprintsthen calls itselfincrementing the low variable in its argument in generaliteration is more efficienthoweverrecursive functions are often easier to understand and write recursive functions are also useful for manipulating recursive data structures such as linked lists and treesas we will see generators and co-routines we can create functions that do not just return one resultbut rather an entire sequence of resultsby using the yield statement these functions are called generators python contains generator functionswhich are an easy way to create iterators and they are especially useful as replacement for unworkably long lists generator yields items rather than build lists for examplethe following code shows why we might choose to use generator as opposed to creating list |
13,509 | compares the running time of list compared to generator import time #generator function creates an iterator of odd numbers between and def oddgen(nm)while myield + #builds list of odd numbers between and def oddlst( , )lst=[while <mlst append(nn += return lst #the time it takes to perform sum on an iterator =time time(sum(oddgen( , )print("time to sum an iterator% (time time( )#the time it takes to build and sum list =time time(sum(oddlst( , )print("time to build and sum list% (time time( )this prints out the followingas we can seebuilding list to do this calculation takes significantly longer the performance improvement as result of using generators is because the values are generated on demandrather than saved as list in memory calculation can begin before all the elements have been generated and elements are generated only when they are needed in the preceding examplethe sum method loads each number into memory when it is needed for the calculation this is achieved by the generator object repeatedly calling the __next__(special method generators never return value other than none typicallygenerator objects are used in for loops for examplewe can make use of the oddcount generator function created in the preceding code to print out odd integers between and for in oddcount( , ):print( |
13,510 | we can also create generator expressionwhichapart from replacing square brackets with parenthesesuses the same syntax and carries out the same operation as list comprehensions generator expressionshoweverdo not create listthey create generator object this object does not create the databut rather creates that data on demand this means that generator objects do not support sequence methods such as append(and insert(you canhoweverchange generator into list using the list(functionclasses and object programming classes are way to create new kinds of objects and they are central to object-oriented programming class defines set of attributes that are shared across instances of that class typicallyclasses are sets of functionsvariablesand properties the object-oriented paradigm is compelling because it gives us concrete way to think about and represent the core functionality of our programs by organizing our programs around objects and data rather than actions and logicwe have robust and flexible way to build complex applications the actions and logic are still present of coursebut by embodying them in objectswe have way to encapsulate functionalityallowing objects to change in very specific ways this makes our code less error-proneeasier to extend and maintainand able to model real-world objects classes are created in python using the class statement this defines set of shared attributes associated with collection of class instances class usually consists of number of methodsclass variablesand computed properties it is important to understand that defining class does notby itselfcreate any instances of that class to create an instancea variable must be assigned to class the class body consists of series of statements that execute during the class definition the functions defined inside class are called instance methods they apply some operations to the class instance by passing an instance of that class as the first argument this argument is called self by conventionbut it can be any legal identifier here is simple example |
13,511 | class employee(object)numemployee def __init__(selfnamerate)self owed self name name self rate=rate employee numemployee + def __del__(self)employee numemployee - def hours(selfnumhours)self owed +numhours self rate return(" hours workednumhoursdef pay(self)self owed return("payed % self nameclass variablessuch as numemployeeshare values among all the instances of the class in this examplenumemployee is used to count the number of employee instances note that the employee class implements the __init__ and __del__ special methodswhich we will discuss in the next section we can create instances of the employee objectsrun methodsand return class and instance variables by doing the following |
13,512 | special methods we can use the dir(objectfunction to get list of attributes of particular object the methods that begin and end with two underscores are called special methods apart from the following exceptionspecial methodare generally called by the python interpreter rather than the programmerfor examplewhen we use the operatorwe are actually invoking call to __add__(for examplerather than using my_object __len__(we can use len(my_objectusing len(on string object is actually much faster because it returns the value representing the object' size in memoryrather than making call to the object' __len__ method the only special method we actually call in our programsas common practiceis the __init__ methodto invoke the initializer of the superclass in our own class definitions it is strongly advised not to use the double underscore syntax for your own objects because of potential current or future conflicts with python' own special methods we mayhoweverwant to implement special methods in custom objectsto give them some of the behavior of built-in types in the following codewe create class that implements the __repr__ method this method creates string representation of our object that is useful for inspection purposesclass my_class()def __init__(selfgreet)self greet greet def __repr__(self)return ' custom object (% )(self greetwhen we create an instance of this object and inspect itwe can see we get our customized string representation notice the use of the % format placeholder to return the standard representation of the object this is useful and best practicebecausein this caseit shows us that the greet object is string indicated by the quotation marks |
13,513 | inheritance it is possible to create new class that modifies the behavior of an existing class through inheritance this is done by passing the inherited class as an argument in the class definition it is often used to modify the behavior of existing methodsfor exampleclass specialemployee(employee)def hours(selfnumhours)self owed +numhours self rate return(" hours workednumhoursan instance of the specialemployee class is identical to an employee instance except for the changed hours(method for subclass to define new class variablesit needs to define an __init__(methodas followsclass specialemployee(employee)def __init__(self,name,ratebonus)employee __init__(selfnamerate#calls the base classes self bonus bonus def hours(selfnumhours)self owed +numhours self rate self bonus return(" hours workednumhoursnotice that the methods of the base class are not automatically invoked and it is necessary for the derived class to call them we can test for class membership using the built-in function isintance(obj obj this returns true if obj belongs to the class of obj or any class derived from obj within class definitionit is assumed that all methods operate on the instancebut this is not requirement there arehoweverother types of methodsstatic methods and class methods static method is just an ordinary function that just happens to be defined in class it does not perform any operations on the instance and it is defined using the @staticmethod class decorator static methods cannot access the attributes of an instanceso their most common usage is as convenience to group utility functions together |
13,514 | class methods operate on the class itselfnot the instancein the same way that class variables are associated with the classes rather than instances of that class they are defined using the @classmethod decoratorand are distinguished from instance methods in that the class is passed as the first argument this is named cls by convention class aexp(object)base= @classmethod def exp(cls, )return(cls base**xclass bexp(aexp)base= the class bexp inherits from the aexp class and changes the base class variable to we can run the parent class' exp(method as followsalthough this example is little contrivedthere are several reasons why class methods may be useful for examplebecause subclass inherits all the same features of its parentthere is the potential for it to break inherited methods using class methods is way to define exactly what methods are run data encapsulation and properties unless otherwise specifiedall attributes and methods are accessible without restriction this also means that everything defined in base class is accessible from derived class this may cause problems when we are building object-oriented applications where we may want to hide the internal implementation of an object this can lead to namespace conflicts between objects defined in derived classes with the base class to prevent thisthe methods we define private attributes with have double underscoresuch as __privatemethod(these method names are automatically changed to _classname__privatemethod(to prevent name conflicts with methods defined in base classes be aware that this does not strictly hide private attributesrather it just provides mechanism for preventing name conflicts |
13,515 | it is recommended to use private attributes when using class property to define mutable attributes property is kind of attribute that rather than returning stored valuecomputes its value when called for examplewe could redefine the exp(property with the followingclass bexp(aexp)__base= def __exp(self)return( **cls basein this we have looked at some of the fundamentals of the python programming languagefrom basic operations to functionsclassesand objects in python in the next we will examinein detailthe built-in data structures of python summary this has given us good foundation and introduction into python programming we covered the use of variableslistsa couple of control structuresand learned how to use conditionals statement the various kinds of objects were discussedtogether with some materials on the object-oriented aspects of the python language we created our own objects and inherited from them there is still more that python offers as we prepare to examine the later on some implementations of algorithmsthe next will focus on numberssequencesmapsand sets these are also data types in python that prove useful when organizing data for series of operations |
13,516 | python data types and structures in this we are going to examine the python data types in detail we have already been introduced to two data typesthe stringstr()and list(it is often the case where we want more specialized objects to represent our data in addition to the built-in typesthere are several internal modules that allow us to address common issues when working with data structures firstwe are going to review some operations and expressions that are common to all data types operations and expressions there are number of operations that are common to all data types for exampleall data typesand generally all objectscan be tested for truth value in some way the following are values that python considers falsethe none type false an integerfloator complex zero an empty sequence or mapping an instance of user-defined class that defines __len__(or __bool__(method that returns zero or false all other values are considered true |
13,517 | boolean operations boolean operation returns value of eighter true or false boolean operations are ordered in priorityso if more than one boolean operation occurs in an expressionthe operation with the highest priority will occur first the following table outlines the three boolean operators in descending order of priorityoperator example not returns true if is falsereturns false otherwise and returns true if both and are truereturns false otherwise or returns true if either or is truereturns false otherwise both the and operator and the or operator use "short-circuitingwhen evaluating an expression this means python will only evaluate an operator if it needs to for exampleif is true then in an expression or ythe does not get evaluated since the expression is obviously true in similar wayin an expression and where is falsethe interpreter will simply evaluate and return falsewithout evaluating comparison and arithmetic operators the standard arithmetic operators (+-*/work with all python numeric types the /operator gives an integer quotient(for example / returns )the exponent operator is *yand the modulus operatorgiven by breturns the remainder of the division / the comparison operators (>===and !=work with numbersstringslistsand other collection objects and return true if the condition holds for collection objectsthese operators compare the number of elements and the equivalence operator = returns true if each collection object is structurally equivalentand the value of each element is identical membershipidentityand logical operations membership operators (innot intest for variables in sequencessuch as lists or strings do what you would expectx in returns true if variable is found in the is operator compares object identity for examplethe following snippet shows contrast equivalence with object identity |
13,518 | built-in data types python data types can be divided into three categoriesnumericsequenceand mapping there is also the none object that represents nullor absence of value it should not be forgotten either that other objects such as classesfilesand exceptions can also properly be considered typeshoweverthey will not be considered here every value in python has data type unlike many programming languagesin python you do not need to explicitly declare the type of variable python keeps track of object types internally python built-in data types are outlined in the following tablecategory name description none none the null object numeric int integer float floating point number complex complex number bool boolean (truefalsesequences str mapping string of characters list list of arbitrary objects tuple group of arbitrary items range creates range of integers dict dictionary of key-value pairs |
13,519 | set mutableunordered collection of unique items frozenset immutable set none type the none type is immutable and has one valuenone it is used to represent the absence of value it is returned by objects that do not explicitly return value and evaluates to false in boolean expressions it is often used as the default value in optional arguments to allow the function to detect whether the caller has passed value numeric types all numeric typesapart from boolare signed and they are all immutable booleans have two possible valuestrue and false these values are mapped to and respectively the integer typeintrepresents whole numbers of unlimited range floating point numbers are represented by the native double precision floating point representation of the machine complex numbers are represented by two floating point numbers they are assigned using the operator to signify the imaginary part of the complex numberfor examplea + we can access the real and imaginary parts with real and imagrespectively representation error it should be noted that the native double precision representation of floating point numbers leads to some unexpected results for exampleconsider the following |
13,520 | this is result of the fact that most decimal fractions are not exactly representable as binary fractionwhich is how most underlying hardware represents floating point numbers for algorithms or applications where this may be an issuepython provides decimal module this module allows for the exact representation of decimal numbers and facilitates greater control properties such as rounding behaviornumber of significant digitsand precision it defines two objectsa decimal typerepresenting decimal numbersand context typerepresenting various computational parameters such as precisionroundingand error handling an example of its usage can be seen in the following snippethere we have created global context and set the precision to the decimal object can be treated pretty much as you would treat an int or float they are subject to all the same mathematical operations and can be used as dictionary keysplaced in setsand so on in additiondecimal objects also have several methods for mathematical operationssuch as natural exponentsx exp()natural logarithmsx ln()and base logarithmsx log (python also has fractions module that implements rational number type the following example shows several ways to create fractionsit is also worth mentioning here the numpy extension this has types for mathematical objects such as arraysvectorsand matrixesand capabilities for linear algebracalculation of fourier transformseigenvectorslogical operationsand much more |
13,521 | sequences sequences are ordered sets of objects indexed by non-negative integers lists and tuples are sequences of arbitrary objectsstrings are sequences of characters stringtupleand range objects are immutable all sequence types have number of operations in common for all sequencesthe indexing and slicing operators apply as described in the previous note that for the immutable typesany operation will only return value rather than actually change the value all sequences have the following methodsmethod description len(snumber of elements in min( [,default=objkey=func]the minimum value in (alphabetically for stringsmax( [,default=objkey=func]maximum value in (alphabetically for stringssum( ,[,start= ]the sum of the elements (returns typeerror if is not numericall(sreturns true if all elements in are true (that isnot falseor nullany(schecks whether any item in is true in additionall sequences support the following operationsoperation description concatenates two sequences of the same type make copies of swhere is an integer vn unpacks variables from to and so on [iindexing-returns element of [ : :strideslicing returns elements between and with optional stride in returns true if element is in not in returns true if element is not in |
13,522 | tuples tuples are immutable sequences of arbitrary objects they are indexed by integers greater than zero tuples are hashablewhich means we can sort lists of them and they can be used as keys to dictionaries syntacticallytuples are just comma-separated sequence of valueshoweverit is common practice to enclose them in parenthesestpl(' '' '' 'it is important to remember to use trailing comma when creating tuple with one elementfor examplet (' ',without the trailing commathis would be interpreted as string we can also create tuple using the built-in function tuple(with no argumentthis creates an empty tuple if the argument to tuple(is sequence then this creates tuple of elements of that sequencefor examplemost operatorssuch as those for slicing and indexingwork as they do on lists howeverbecause tuples are immutabletrying to modify an element of tuple will give you typeerror we can compare tuples in the same way that we compare other sequencesusing the ==and operators an important use of tuples is to allow us to assign more than one variable at time by placing tuple on the left-hand side of an assignmentfor examplewe can actually use this multiple assignment to swap values in tuplefor examplea valueerror will be thrown if the number of values on each side of the assignment are not the same |
13,523 | dictionaries dictionaries are arbitrary collections of objects indexed by numbersstringsor other immutable objects dictionaries themselves are mutablehowevertheir index keys must be immutable the following table contains all the dictionary methods and their descriptionsmethod description len(dnumber of items in clear(removes all items from copy(makes shallow copy of fromkeys( [,value]returns new dictionary with keys from sequence and values set to value get( [, ]returns [kif foundor else returns vor none if is not given items(returns sequence of key:value pairs in keys(returns sequence of keys in pop( [,default]returns [kand removes it from if [kis not foundit returns default or raises keyerror popitem(removes random key:value pair from and returns it as tuple setdefault( [, ]returns [kif [kis not foundit returns and sets [kto update(badds all objects from to values(returns sequence of values in python dictionaries are the only built-in mapping type and they are similar to hash tables or associative arrays found in other languages they can be thought of as mapping from set of keys to set of values they are created using the syntax {key:valuefor examplethe following creates dictionary mapping words to numeralsd ={'one' 'two' 'three' creates dictionary |
13,524 | we can add keys and values as followsd['four']= #add an item or update multiple values using the followingd update({'five' 'six' }#add multiple items when we inspect dwe get the followingwe can test for the occurrence of value using the in operatorfor exampleit should be noted that the in operatorwhen applied to dictionariesworks in slightly different way to when it is applied to list when we use the in operator on listthe relationship between the time it takes to find an element and the size of the list is considered linear that isas the size of the list gets biggerthe corresponding time it takes to find an element growsat mostlinearly the relationship between the time an algorithm takes to run compared to the size of its input is often referred to as its time complexity we will talk more about this important topic in the next (and subsequent in contrast to the list objectwhen the in operator is applied to dictionariesit uses hashing algorithm and this has the effect of the increase in time for each lookup almost independent of the size of the dictionary this makes dictionaries extremely useful as way to work with large amounts of indexed data we will talk more about this important topic of rates of growth hashing in lists and pointer structuresand implementationsapplications and tools notice when we print out the key:value pairs of the dictionary it does so in no particular order this is not problem since we use specified keys to look up each dictionary value rather than an ordered sequence of integers as is the case for strings and lists |
13,525 | sorting dictionaries if we want to do simple sort on either the keys or values of dictionarywe can do the followingnote that the first line in the preceding code sorts the keys according to alphabetical orderand the second line sorts the values in order of integer value the sorted(method has two optional arguments that are of interestkey and reverse the key argument has nothing to do with the dictionary keysbut rather is way of passing function to the sort algorithm to determine the sort order for examplein the following codewe use the __getitem__ special method to sort the dictionary keys according to the dictionary valuesessentiallywhat the preceding code is doing is for every key in to use the corresponding value to sort we can also sort the values according to the sorted order of the dictionary keys howeversince dictionaries do not have method to return key by using its valuethe equivalent of the list index method for listsusing the optional key argument to do this is little tricky an alternative approach is to use list comprehensionas the following example demonstratesthe sorted(method also has an optional reverse argumentand unsurprisinglythis does exactly what it saysreverses the order of the sorted listfor example |
13,526 | nowlet' say we are given the following dictionaryenglish words as keys and french words as values our task is to place these string values in correct numerical orderd ={'one':'uno'two':'deux''three':'trois''four''quatre''five''cinq''six':'six'of coursewhen we print this dictionary outit will be unlikely to print in the correct order because all keys and values are stringswe have no context for numerical ordering to place these items in correct orderwe need to use the first dictionary we createdmapping words to numerals as way to order our english to french dictionarynotice we are using the values of the first dictionarydto sort the keys of the second dictionaryd since our keys in both dictionaries are the samewe can use list comprehension to sort the values of the french to english dictionarywe canof coursedefine our own custom method that we can use as the key argument to the sorted method for examplehere we define function that simply returns the last letter of stringdef corder(string)return(string[len(string)- ]we can then use this as the key to our sorted function to sort each element by its last letter |
13,527 | dictionaries for text analysis common use of dictionaries is to count the occurrences of like items in sequencea typical example is counting the occurrences of words in body of text the following code creates dictionary where each word in the text is used as key and the number of occurrences as its value this uses very common idiom of nested loops here we are using it to traverse the lines in file in an outer loop and the keys of dictionary on the inner loopdef wordcount(fname)tryfhand=open(fnameexceptprint('file cannot be opened'exit(countdict(for line in fhandwords line split(for word in wordsif word not in countcount[word elsecount[word+ return(countthis will return dictionary with an element for each unique word in the text file common task is to filter items such as these into subsets we are interested in you will need text file saved in the same directory as you run the code here we have used alice txta short excerpt from alice in wonderland to obtain the same resultsyou can download alice txt from davejulian net/bo or use text file of your own in the following codewe create another dictionaryfilteredcontaining subset of items from countcount=wordcount('alice txt'filtered key:value for keyvalue in count items(if value value when we print the filtered dictionarywe get the following and |
13,528 | note the use of the dictionary comprehension used to construct the filtered dictionary dictionary comprehensions work in an identical way to the list comprehensions we looked at in python objectstypesand expressions sets sets are unordered collections of unique items sets are themselves mutablewe can add and remove items from themhoweverthe items themselves must be immutable an important distinction with sets is that they cannot contain duplicate items sets are typically used to perform mathematical operations such as intersectionuniondifferenceand complement unlike sequence typesset types do not provide any indexing or slicing operations there are also no keys associated with valuesas is the case with dictionaries there are two types of set objects in pythonthe mutable set object and the immutable frozenset object sets are created using comma-separated values within curly braces by the waywe cannot create an empty set using ={}because this will create dictionary to create an empty setwe write either =set(or =frozenset(methods and operations of sets are described in the following tablemethod operators description len(sreturns the number of elements in copy(returns shallow copy of difference(ts tt returns set of all items in but not in intersection(treturns set of all items in both and isdisjoint(treturns true if and have no items in common issubset(ts < ( !treturns true if all items in are also in issuperset(ts > ( !treturns true if all items in are also in |
13,529 | symmetric_difference(ts returns set of all items that are in or tbut not both union(treturns set of all items in or in the preceding tablethe parameter can be any python object that supports iteration and all methods are available to both set and frozenset objects it is important to be aware that the operator versions of these methods require their arguments to be setswhereas the methods themselves can accept any iterable type for examples [ , , ]for any set swill generate an unsupported operand type using the equivalent difference([ , , ]will return result mutable set objects have additional methodsdescribed in the following tablemethod description add(itemadds item to has no effect if item is already present clear(removes all items from difference_update(tremoves all items in that are also in discard(itemremoves item from intersection_update(tremoves all items from that are not in the intersection of and pop(returns and removes an arbitrary item from remove(itemremoves item from symetric_difference_update(tremoves all items from that are not in the symmetric difference of and update(tadds all the items in an iterable object to |
13,530 | the following example demonstrates some simple set operations and their resultsnotice that the set object does not care that its members are not all of the same typeas long as they are all immutable if you try to use mutable object such as list or dictionaries in setyou will receive an unhashable type error hashable types all have hash value that does not change throughout the lifetime of the instance all built-in immutable types are hashable all built-in mutable types are not hashableso they cannot be used as elements of sets or keys to dictionaries notice also in the preceding code that when we print out the union of and there is only one element with the value 'abthis is natural property of sets in that they do not include duplicates in addition to these built-in methods there are number of other operations that we can perform on sets for exampleto test for membership of setuse the followingwe can loop through elements in set using the following |
13,531 | immutable sets python has an immutable set type called frozenset it works pretty much exactly like set apart from not allowing methods or operations that change values such as the add(or clear(methods there are several ways that this immutability can be useful for examplesince normal sets are mutable and therefore not hashablethey cannot be used as members of other sets the frozenseton the other handis immutable and therefore able to be used as member of setalso the immutable property of frozenset means we can use it for key to dictionaryfor examplemodules for data structures and algorithms in addition to the built-in typesthere are several python modules that we can use to extend these built-in types and functions in many casesthese python modules may offer efficiency and programming advantages that allow us to simplify our code |
13,532 | so farwe have looked at the built-in datatypes of stringslistssetsand dictionaries as well as the decimal and fractions modules they are often described by the term abstract data types (adtsadts can be considered as mathematical specifications for the set of operations that can be performed on data they are defined by their behavior rather than their implementation in addition to the adts that we have looked atthere are several python libraries that provide extensions to the built-in datatypes these will be discussed in the following section collections the collections module provides more specializedhighperformance alternatives for the built-in data types as well as utility function to create named tuples the following table lists the datatypes and operations of the collections module and their descriptionsdatatype or operation description namedtuple(creates tuple subclasses with named fields deque lists with fast appends and pops either end chainmap dictionary like class to create single view of multiple mappings counter dictionary subclass for counting hashable objects ordereddict dictionary subclass that remembers the entry order defaultdict dictionary subclass that calls function to supply missing values userdict userlist userstring these three data types are simply wrappers for their underlying base classes their use has largely been supplanted by the ability to subclasas their respective base classes directly can be used to access the underlying object as an attribute deques double-ended queuesor deques (usually pronounced decks)are list-like objects that support thread-safememory-efficient appends deques are mutable and support some of the operations of listssuch as indexing deques can be assigned by indexfor exampledq[ zhoweverwe cannot directly slice deques for exampledq[ : results in typeerror (we will look at way to return slice from deque as list shortly |
13,533 | the major advantage of deques over lists is that inserting items at the beginning of deque is much faster than inserting items at the beginning of listalthough inserting items at the end of deque is very slightly slower than the equivalent operation on list deques are threadsafe and can be serialized using the pickle module useful way of thinking about deques is in terms of populating and consuming items items in deques are usually populated and consumed sequentially from either endwe can use the pop(and popleft(methods for consuming items in the dequefor examplewe can also use the rotate(nmethod to move and rotate all items of steps to the right for positive values of the integer nor left for negative values of the leftusing positive integers as the argumentfor example |
13,534 | note that we can use the rotate and pop methods to delete selected elements also worth knowing is simple way to return slice of dequeas listwhich can be done as followsthe itertools islice method works in the same way that slice works on listexcept rather than taking list for an argumentit takes an iterable and returns selected valuesby start and stop indicesas list useful feature of deques is that they support maxlen optional parameter that restricts the size of the deque this makes it ideally suited to data structure known as circular buffer this is fixed-size structure that is effectively connected end to end and they are typically used for buffering data streams the following is basic exampledq =deque([],maxlen= for in range( )dq append(iprint(dq this prints out the followingin this examplewe are populating from the right and consuming from the left notice that once the buffer is fullthe oldest values are consumed firstand values are replaced from the right we will look at circular buffers again in lists and pointer structuresby implementing circular lists |
13,535 | chainmaps the collections chainmap class was added in python and it provides way to link number of dictionariesor other mappingsso that they can be treated as one object in additionthere is maps attributea new_child(methodand parents property the underlying mappings for chainmap objects are stored in list and are accessible using the maps[iattribute to retrieve the ith dictionary note that even though dictionaries themselves are unorderedchainmaps are an ordered list of dictionaries chainmap is useful in applications where we are using number of dictionaries containing related data the consuming application expects data in terms of prioritywhere the same key in two dictionaries is given priority if it occurs at the beginning of the underlying list chainmap is typically used to simulate nested contexts such as when we have multiple overriding configuration settings the following example demonstrates possible use case for chainmapthe advantage of using chainmapsrather than just dictionaryis that we retain previously set values adding child context overrides values for the same keybut it does not remove it from the data structure this can be useful for when we may need to keep record of changes so that we can easily roll back to previous setting we can retrieve and change any value in any of the dictionaries by providing the map(method with an appropriate index this index represents dictionary in the chainmap alsowe can retrieve the parent settingthat isthe default settingsby using the parents(method |
13,536 | counter objects counter is subclass of dictionary where each dictionary key is hashable object and the associated value is an integer count of that object there are three ways to initialize counter we can pass it any sequence objecta dictionary of key:value pairsor tuple of the format (object value)for examplewe can also create an empty counter object and populate it by passing its update method an iterable or dictionaryfor example |
13,537 | notice how the update method adds the counts rather than replacing them with new values once the counter is populatedwe can access stored values in the same way we would for dictionariesfor examplethe most notable difference between counter objects and dictionaries is that counter objects return zero count for missing items rather than raising key errorfor examplewe can create an iterator out of counter object by using its elements(method this returns an iterator where counts below one are not included and the order is not guaranteed in the following codewe perform some updatescreate an iterator from counter elementsand use sorted(to sort the keys alphabetically |
13,538 | two other counter methods worth mentioning are most_common(and subtract(the most common method takes positive integer argument that determines the number of most common elements to return elements are returned as list of (key ,valuetuples the subtract method works exactly like update except instead of adding valuesit subtracts themfor exampleordered dictionaries the important thing about ordered dictionaries is that they remember the insertion orderso when we iterate over themthey return values in the order they were inserted this is in contrast to normal dictionarywhere the order is arbitrary when we test to see whether two dictionaries are equalthis equality is only based on their keys and valueshoweverwith an ordereddictthe insertion order is also considered an equality test between two ordereddicts with the same keys and values but different insertion order will return falsesimilarlywhen we add values from list using updatethe ordereddict will retain the same order as the list this is the order that is returned when we iterate the valuesfor example |
13,539 | the ordereddict is often used in conjunction with the sorted method to create sorted dictionary for examplein the following example we use lambda function to sort on the valueshere we use numerical expression to sort the integer valuesdefaultdict the defaultdict object is subclass of dict and therefore they share methods and operations it acts as convenient way to initialize dictionaries with dictpython will throw keyerror when attempting to access key that is not already in the dictionary the defaultdict overrides one method__missing__(key)and creates new instance variabledefault_factory with defaultdictrather than throw an errorit will run the functionsupplied as the default_factory argumentwhich will generate value simple use of defaultdict is to set default_factory to int and use it to quickly tally the counts of items in the dictionaryfor example |
13,540 | you will notice that if we tried to do this with an ordinary dictionarywe would get key error when we tried to add the first key the int we supplied as an argument to default dict is really the function int(that simply returns zero we canof coursecreate function that will determine the dictionary' values for examplethe following function returns true if the supplied argument is primary colorthat is redgreenor blueor returns false otherwisedef isprimary( )if ( ='red'or ( ='blue'or ( ='green')return true elsereturn false we can now create new defaultdict object and use the isprimary function to populate itnamed tuples the namedtuple method returns tuple-like object that has fields accessible with named indexes as well as the integer indexes of normal tuples this allows for code that isto certain extentself-documenting and more readable it can be especially useful in an application where there is large number of tuples and we need to easily keep track of what each tuple represents the namedtuple inherits methods from tuple and it is backward-compatible with tuple |
13,541 | the field names are passed to the namedtuple method as comma and/or whitespace separated values they can also be passed as sequence of strings field names are single strings and they can be any legal python identifier that does not begin with digit or an underscore typical example is shown herethe namedtuple method take two optional boolean argumentsverbose and rename when verbose is set to true then the class definition is printed when it is built this argument is depreciated in favor of using the __source attribute when the rename argument is set to true then any invalid field names will be automatically replaced with positional arguments as an examplewe attempt to use def as field name this would normally generate an errorbut since we have assigned rename to truethe python interpreter allows this howeverwhen we attempt to look up the def valuewe get syntax errorsince def is reserved keyword the illegal field name has been replaced by field name created by adding an underscore to the positional valuein addition to the inherited tuple methodsthe named tuple also defines three methods of its own_make(asdict()and _replace these methods begin with an underscore to prevent potential conflicts with field names the _make(method takes an iterable as an argument and turns it into named tuple objectfor example |
13,542 | the _asdict method returns an ordereddict with the field names mapped to index keys and the values mapped to the dictionary valuesfor examplethe _replace method returns new instance of the tuplereplacing the specified valuesfor examplearrays the array module defines datatype array that is similar to the list datatype except for the constraint that their contents must be of single type of the underlying representationas is determined by the machine architecture or underlying implementation the type of an array is determined at creation time and it is indicated by one of the following type codescode type python type minimum bytes 'bsigned char int 'bunsigned char int 'upy_unicode unicode character 'hsigned short int 'hunsigned short int |
13,543 | 'isigned int int 'iunsigned int int 'lsigned long int 'lunsigned long int 'qsigned long long int 'qunsigned lon long int 'ffloat float 'ddouble float the array objects support the following attributes and methodsattribute or method description typecode the typecode character used to create the array itemsize sizein bytesof items stored in the array append(xappends item to the end of the array buffer_info(returns the memory location and length of the buffer used to store the array byteswap(swaps the byte order of each item used for writing to machine or file with different byte order count(xreturns the number of occurrences of in extend(bappends any iterablebto the end of array frombytes(sappends items from stringsas an array of machine values fromfile(fnreads itemsas machine valuesfrom file objectfand appends them to raises an eoferror if there are fewer than items in fromlist(lappends items from list fromunicode(sextends with unicode string array must be of type or else valueerror is raised index(xreturns the first (smallestindex of item insert(ixinserts item before index |
13,544 | pop([ ]removes and returns items with index defaults to the last item ( - if not specified remove(xremoves the first occurrence of item reverse(reverses the order of items tobytes(convert the array to machine values and returns the bytes representation tofile(fwrites all itemsas machine valuesto file object tolist(converts the array to list tounicode(convert an array to unicode string the array type must be 'uor else valueerror is raised array objects support all the normal sequence operations such as indexingslicingconcatenationand multiplication using arraysas opposed to listsis much more efficient way of storing data that is all of the same type in the following examplewe have created an integer array of the digits from to million minus and an identical list storing million integers in an integer array requires around of the memory of an equivalent listbecause we are interested in saving spacethat iswe are dealing with large datasets and limited memory sizewe usually perform in-place operations on arraysand only create copies when we need to typicallyenumerate is used to perform an operation on each element in the following snippetwe perform the simple operation of adding one to each item in the array |
13,545 | it should be noted that when performing operations on arrays that create listssuch as list comprehensionsthe memory efficiency gains of using an array in the first place will be negated when we need to create new data objecta solution is to use generator expression to perform the operationfor examplearrays created with this module are unsuitable for work that requires matrix of vector operations in the next we will build our own abstract data type to deal with these operations also important for numerical work is the numpy extensionavailable at www numpy org summary in the last two we have examined the language features and data types of python we have looked at the built-in data types and some internal python modulesmost notably the collections module there are also several other python modules that are relevant to the topic of this bookbut rather than examining them separatelytheir use and functionality should become self-evident as we begin using them there are also number of external libraries such as the scipy stackandlikewisei will attempt to explain their basic functionality as we begin to apply them in the next we will introduce the basic theory and techniques of algorithm design |
13,546 | principles of algorithm design why do we want to study algorithm designthere are of course many reasonsand our motivation for learning something is very much dependent on our own circumstances there are without doubt important professional reasons for being interested in algorithm design algorithms are the foundations of all computing we think of computer as being piece of hardwarea hard drivememory chipsprocessorsand so on howeverthe essential componentthe thing thatif missingwould render modern technology impossibleis algorithms the theoretical foundation of algorithmsin the form of the turing machinewas established several decades before digital logic circuits could actually implement such machine the turing machine is essentially mathematical model thatusing predefined set of rulestranslates set of inputs into set of outputs the first implementations of turing machines were mechanical and the next generation may likely see digital logic circuits replaced by quantum circuits or something similar regardless of the platformalgorithms play central predominant role another aspect is the effect algorithms have in technological innovation as an obvious exampleconsider the page rank search algorithma variation of which the google search engine is based on using this and similar algorithms allows researchersscientiststechniciansand others to quickly search through vast amounts of information extremely quickly this has massive effect on the rate at which new research can be carried outnew discoveries madeand new innovative technologies developed |
13,547 | the study of algorithms is also important because it trains us to think very specifically about certain problems it can serve to increase our mental and problem solving abilities by helping us isolate the components of problem and define relationships between these components in summarythere are four broad reasons for studying algorithms they are essential for computer science and intelligent systems they are important in many other domains (computational biologyeconomicsecologycommunicationsecologyphysicsand so on they play role in technology innovation they improve problem solving and analytical thinking algorithmsin their simplest formare just sequence of actionsa list of instructions it may just be linear construct of the form do xthen do ythen do zthen finish howeverto make things more useful we add clauses to the effect ofx then do yin python the if-else statements herethe future course of action is dependent on some conditionssay the state of data structure to this we also add the operationiterationthe whileand for statements expanding our algorithmic literacy further we add recursion recursion can often achieve the same result as iterationhoweverthey are fundamentally different recursive function calls itselfapplying the same function to progressively smaller inputs the input of any recursive step is the output of the previous recursive step essentiallywe can say that algorithms are composed of the following four elementssequential operations actions based on the state of data structure iterationrepeating an action number of times recursioncalling itself on subset of inputs algorithm design paradigms in generalwe can discern three broad approaches to algorithm design they aredivide and conquer greedy algorithms dynamic programming as the name suggeststhe divide and conquer paradigm involves breaking problem into smaller sub problemsand then in some way combining the results to obtain global solution this is very common and natural problem solving techniqueand isarguablythe most commonly used approach to algorithm design |
13,548 | greedy algorithms often involve optimization and combinatorial problemsthe classic example is applying it to the traveling salesperson problemwhere greedy approach always chooses the closest destination first this shortest path strategy involves finding the best solution to local problem in the hope that this will lead to global solution the dynamic programming approach is useful when our sub problems overlap this is different from divide and conquer rather than break our problem into independent sub problemswith dynamic programmingintermediate results are cached and can be used in subsequent operations like divide and conquer it uses recursionhoweverdynamic programming allows us to compare results at different stages this can have performance advantage over divide and conquer for some problems because it is often quicker to retrieve previously calculated result from memory rather than having to recalculate it recursion and backtracking recursion is particularly useful for divide and conquer problemshoweverit can be difficult to understand exactly what is happeningsince each recursive call is itself spinning off other recursive calls at the core of recursive function are two types of casesbase caseswhich tell the recursion when to terminateand recursive cases that call the function they are in simple problem that naturally lends itself to recursive solution is calculating factorials the recursive factorial algorithm defines two casesthe base case when is zeroand the recursive case when is greater than zero typical implementation is the followingdef factorial( )#test for base case if == return make calculation and recursive call fn*factorial( - print(freturn(ffactorial( |
13,549 | this code prints out the digits to calculate requires four recursive calls plus the initial parent call on each recursiona copy of the methods variables is stored in memory once the method returns it is removed from memory the following is way we can visualize this processit may not necessarily be clear if recursion or iteration is better solution to particular problemafter all they both repeat series of operations and both are very well suited to divide and conquer approaches to algorithm design iteration churns away until the problem is done recursion breaks the problem down into smaller and smaller chunks and then combines the results iteration is often easier for programmersbecause control stays local to loopwhereas recursion can more closely represent mathematical concepts such as factorials recursive calls are stored in memorywhereas iterations are not this creates trade off between processor cycles and memory usageso choosing which one to use may depend on whether the task is processor or memory intensive the following table outlines the key differences between recursion and iterationrecursion iteration terminates when base case is reached terminates when defined condition is met each recursive call requires space in memory each iteration is not stored in memory an infinite recursion results in stack overflow error an infinite iteration will run while the hardware is powered some problems are naturally better suited to recursive solutions iterative solutions may not always be obvious |
13,550 | backtracking backtracking is form of recursion that is particularly useful for types of problems such as traversing tree structureswhere we are presented with number of options at each nodefrom which we must choose one subsequently we are presented with different set of optionsand depending on the series of choices made either goal state or dead end is reached if it is the latterwe must backtrack to previous node and traverse different branch backtracking is divide and conquer method for exhaustive search importantly backtracking prunes branches that cannot give result an example of back tracking is given in the following example herewe have used recursive approach to generating all the possible permutations of given stringsof given length ndef bitstr(ns)if = return return digit bits for digit in bitstr( , )for bits in bitstr( , )print (bitstr( ,'abc')this generates the following outputnotice the double list compression and the two recursive calls within this comprehension this recursively concatenates each element of the initial sequencereturned when with each element of the string generated in the previous recursive call in this sense it is backtracking to uncover previously ingenerated combinations the final string that is returned is all letter combinations of the initial string divide and conquer long multiplication for recursion to be more than just clever trickwe need to understand how to compare it to other approachessuch as iterationand to understand when its use will lead to faster algorithm an iterative algorithm that we are all familiar with is the procedure we learned in primary math classesused to multiply two large numbers that islong multiplication if you rememberlong multiplication involved iterative multiplying and carry operations followed by shifting and addition operation |
13,551 | our aim here is to examine ways to measure how efficient this procedure is and attempt to answer the questionis this the most efficient procedure we can use for multiplying two large numbers togetherin the following figurewe can see that multiplying two digit numbers together requires multiplication operationsand we can generalize to say that an digit number requires approximatelyn multiplication operationsthis method of analyzing algorithmsin terms of the number of computational primitives such as multiplication and additionis important because it gives us way to understand the relationship between the time it takes to complete certain computation and the size of the input to that computation in particularwe want to know what happens when the inputthe number of digitsnis very large this topiccalled asymptotic analysisor time complexityis essential to our study of algorithms and we will revisit it often during this and the rest of this book can we do bettera recursive approach it turns out that in the case of long multiplication the answer is yesthere are in fact several algorithms for multiplying large numbers that require less operations one of the most wellknown alternatives to long multiplication is the karatsuba algorithmfirst published in this takes fundamentally different approachrather than iteratively multiplying single digit numbersit recursively carries out multiplication operations on progressively smaller inputs recursive programs call themselves on smaller subsets of the input the first step in building recursive algorithm is to decompose large number into several smaller numbers the most natural way to do this is to simply split the number in to two halvesthe first half of most significant digitsand second half of least significant digits for exampleour four-digit number becomes pair of two-digit numbers and we can write more general decomposition of any digit numbersx and using the followingwhere is any positive integer less than |
13,552 | so now we can rewrite our multiplication problem xy as followswhen we expand and gather like terms we get the followingmore convenientlywe can write it like thiswhereit should be pointed out that this suggests recursive approach to multiplying two numbers since this procedure does itself involve multiplication specificallythe products acadbcand bd all involve numbers smaller than the input number and so it is conceivable that we could apply the same operation as partial solution to the overall problem this algorithmso farconsists of four recursive multiplication steps and it is not immediately clear if it will be faster than the classic long multiplication approach what we have discussed so far in regards to the recursive approach to multiplicationhas been well known to mathematicians since the late th century the karatsuba algorithm improves on this is by making the following observation we really only need to know three quantitiesz ac =ad +bcand bd to solve equation we need to know the values of abcd only in so far as they contribute to the overall sum and products involved in calculating the quantities and this suggests the possibility that perhaps we can reduce the number of recursive steps it turns out that this is indeed the situation since the products ac and bd are already in their simplest formit seems unlikely that we can eliminate these calculations we can however make the following observation |
13,553 | when we subtract the quantities ac and bdwhich we have calculated in the previous recursive stepwe get the quantity we neednamely (ad bc)this shows that we can indeed compute the sum of ad bc without separately computing each of the individual quantities in summarywe can improve on equation by reducing from four recursive steps to three these three steps are as follows recursively calculate ac recursively calculate bd recursively calculate ( + )( dand subtract ac and bd the following example shows python implementation of the karatsuba algorithmfrom math import log def karatsuba( , )the base case for recursion if or return * #sets nthe number of digits in the highest input number max(int(log ( )+ )int(log ( )+ )rounds up / n_ int(math ceil( )#adds if is uneven if = else #splits the input numbers ab divmod( **n_ cd divmod( **n_ #applies the three recursive steps ac karatsuba( ,cbd karatsuba( ,dad_bc karatsuba(( + ),( + )ac bd #performs the multiplication return ((( ** )*acbd (( **n_ )*(ad_bc)) |
13,554 | to satisfy ourselves that this does indeed workwe can run the following test functionimport random def test()for in range( ) random randint( , ** random randint( , ** expected result karatsuba(xyif result !expectedreturn("failed"return('ok'runtime analysis it should be becoming clear that an important aspect to algorithm design is gauging the efficiency both in terms of space (memoryand time (number of operationsthis second measurecalled runtime performanceis the subject of this section it should be mentioned that an identical metric is used to measure an algorithm' memory performance there are number of ways we couldconceivablymeasure run time and probably the most obvious is simply to measure the time the algorithm takes to complete the major problem with this approach is that the time it takes for an algorithm to run is very much dependent on the hardware it is run on platform-independent way to gauge an algorithm' runtime is to count the number of operations involved howeverthis is also problematic in that there is no definitive way to quantify an operation this is dependent on the programming languagethe coding styleand how we decide to count operations we can use this ideathoughof counting operationsif we combine it with the expectation that as the size of the input increases the runtime will increase in specific way that isthere is mathematical relationship between nthe size of the inputand the time it takes for the algorithm to run much of the discussion that follows will be framed by the following three guiding principles the rational and importance of these principles should become clearer as we proceed these principles are as followsworst case analysis make no assumptions on the input data ignore or suppress constant factors and lower order terms at large inputs higher order terms dominate focus on problems with large input sizes |
13,555 | worst case analysis is useful because it gives us tight upper bound that our algorithm is guaranteed not to exceed ignoring small constant factorsand lower order terms is really just about ignoring the things thatat large values of the input sizendo not contributein large degreeto the overall run time not only does it make our work mathematically easierit also allows us to focus on the things that are having the most impact on performance we saw with the karatsuba algorithm that the number of multiplication operations increased to the square of the sizenof the input if we have four-digit number the number of multiplication operations is an eight-digit number requires operations typicallythoughwe are not really interested in the behavior of an algorithm at small values of nso we most often ignore factors that increase at slower ratessay linearly with this is because at high values of nthe operations that increase the fastest as we increase nwill dominate we will explain this in more detail with an examplethe merge sort algorithm sorting is the subject of sortinghoweveras precursor and as useful way to learn about runtime performancewe will introduce merge sort here the merge sort algorithm is classic algorithm developed over years ago it is still used widely in many of the most popular sorting libraries it is relatively simple and efficient it is recursive algorithm that uses divide and conquer approach this involves breaking the problem into smaller sub problemsrecursively solving themand then somehow combining the results merge sort is one of the most obvious demonstrations of the divide and conquer paradigm the merge sort algorithm consists of three simple steps recursively sort the left half of the input array recursively sort the right half of the input array merge two sorted sub arrays into one typical problem is sorting list of numbers into numerical order merge sort works by splitting the input into two halves and working on each half in parallel we can illustrate this process schematically with the following diagram |
13,556 | here is the python code for the merge sort algorithmdef mergesort( )#base case if the input array is one or zero just return if len( splitting input array print('splitting ' mid len( )// left [:midright [mid:#recursive calls to mergesort for left and right sub arrays mergesort(leftmergesort(right#initalizes pointers for left (iright (jand output array ( initalization operations #traverse and merges the sorted arrays while <len(leftand <len(right)if left right comparison operation if left[iright[ ]if left right assignment operation [ ]=left[ii= + else#if right <left assignment [ ]right[jj= + = + while <len(left) |
13,557 | #assignment operation [ ]=left[ii= + = + while <len(right)#assignment operation [ ]=right[jj= + = + print('merging 'areturn(awe run this program for the following resultsthe problem that we are interested in is how we determine the running time performancethat iswhat is the rate of growth in the time it takes for the algorithm to complete relative to the size of to understand this bit betterwe can map each recursive call onto tree structure each node in the tree is recursive call working on progressively smaller sub problems |
13,558 | each invocation of merge-sort subsequently creates two recursive callsso we can represent this with binary tree each of the child nodes receives sub set of the input ultimately we want to know the total time it takes for the algorithm to complete relative to the size of to begin with we can calculate the amount of work and the number of operations at each level of the tree focusing on the runtime analysisat level the problem is split into two / sub problemsat level there is four / sub problemsand so on the question is when does the recursion bottom outthat iswhen does it reach its base case this is simply when the array is either zero or one the number of recursive levels is exactly the number of times you need to divide by until you get number that is at most this is precisely the definition of log since we are counting the initial recursive call as level the total number of levels is log let' just pause to refine our definitions so far we have been describing the number of elements in our input by the letter this refers to the number of elements in the first level of the recursionthat isthe length of the initial input we are going to need to differentiate between the size of the input at subsequent recursive levels for this we will use the letter or specifically mj for the length of the input at recursive level also there are few details we have overlookedand am sure you are beginning to wonder about for examplewhat happens when / is not an integeror when we have duplicates in our input array it turns out that this does not have an important impact on our analysis herewe will revisit some of the finer details of the merge sort algorithm in design techniques and strategies |
13,559 | the advantage of using recursion tree to analyze algorithms is that we can calculate the work done at each level of the recursion how to define this work is simply as the total number of operations and this of course is related to the size of the input it is important to measure and compare the performance of algorithms in platform independent way the actual run time will of course be dependent on the hardware on which it is run counting the number of operations is important because it gives us metric that is directly related to an algorithm' performanceindependent of the platform in generalsince each invocation of merge sort is making two recursive callsthe number of calls is doubling at each level at the same time each of these calls is working on an input that is half of its parents we can formalize this and say thatfor level where is an integer log nthere are two sub problems each of size / to calculate the total number of operationswe need to know the number of operations encompassed by single merge of two sub arrays let' count the number of operations in the previous python code what we are interested in is all the code after the two recursive calls have been made firstlywe have the three assignment operations this is followed by three while loops in the first loop we have an if else statement and within each of are two operationsa comparison followed by an assignment since there are only one of these sets of operations within the if else statementswe can count this block of code as two operations carried out times this is followed by two while loops with an assignment operation each this makes total of operations for each recursion of merge sort since must be at least the upper bound for the number of operations is it has to be said that this has no pretense at being an exact number we could of course decide to count operations in different way we have not counted the increment operations or any of the housekeeping operationshoweverthis is not so important as we are more concerned with the rate of growth of the runtime with respect to at high values of this may seem little daunting since each call of recursive call itself spins off more recursive callsand seemingly explodes exponentially the key fact that makes this manageable is that as the number of recursive calls doublesthe size of each sub problem halves these two opposing forces cancel out nicely as we can demonstrate to calculate the maximum number of operations at each level of the recursion tree we simply multiply the number of sub problems by the number of operations in each sub problem as follows |
13,560 | importantly this shows thatbecause the cancels out the number of operations at each level is independent of the level this gives us an upper bound to the number of operations carried out on each levelin this example it should be pointed out that this includes the number of operations performed by each recursive call on that levelnot the recursive calls made on subsequent levels this shows that the work doneas the number of recursive calls doubles with each levelis exactly counter balanced by the fact that the input size for each sub problem is halved to find the total number of operations for complete merge sort we simply multiply the number of operations on each level by the number of levels this gives us the followingwhen we expand this outwe get the followingthe key point to take from this is that there is logarithmic component to the relationship between the size of the input and the total running time if you remember from school mathematicsthe distinguishing characteristic of the logarithm function is that it flattens off very quickly as an input variablexincreases in sizethe output variabley increases by smaller and smaller amounts for examplecompare the log function to linear function |
13,561 | in the previous examplemultiplying the nlog component and comparing it to notice how for very low values of nthe time to completet is actually lower for an algorithm that runs in time howeverfor values above about the log function begins to dominateflattening the output until at the comparatively moderate size the performance is more than twice than that of an algorithm running in time notice also that the disappearance of the constant factor is irrelevant at high values of the code used to generate these graphs is as followsimport matplotlib pyplot as plt import math =list(range( , ) =[] =[] plt plot( [ for in xplt plot( [( * )math log( for in ]plt show(you will need to install the matplotlib libraryif it is not installed alreadyfor this to work details can be found at the following addressi encourage you to experiment with this list comprehension expression used to generate the plots for exampleadding the following plot statementplt plot( [( * )math log( for in ] |
13,562 | gives the following outputthe preceding graph shows the difference between counting six operations or seven operations we can see how the two cases divergeand this is important when we are talking about the specifics of an application howeverwhat we are more interested in here is way to characterize growth rates we are not so much concerned with the absolute valuesbut how these values change as we increase in this way we can see that the two lower curves have similar growth rateswhen compared to the top ( curve we say that these two lower curves have the same complexity class this is way to understand and describe different runtime behaviors we will formalize this performance metric in the next section asymptotic analysis there are essentially three things that characterize an algorithm' runtime performance they areworst case use an input that gives the slowest performance best case use an input that givethe best results average case assumes the input is random to calculate each of thesewe need to know the upper and lower bounds we have seen way to represent an algorithm' runtime using mathematical expressionsessentially adding and multiplying operations to use asymptotic analyseswe simply create two expressionsone each for the best and worst cases |
13,563 | big notation the letter "oin big notation stands for orderin recognition that rates of growth are defined as the order of function we say that one function (nis big of another functionf( )and we define this as followsthe functiong( )of the input sizenis based on the observation that for all sufficiently large values of ng(nis bounded above by constant multiple of (nthe objective is to find the smallest rate of growth that is less than or equal to (nwe only care what happens at higher values of the variable represents the threshold below which the rate of growth is not importantthe function (nrepresents the tight upper bound (nin the following plot we see that (nn ( with and is approximately you will also see the notation (no( ( )this describes the fact that ( ( )is really set of functions that include all functions with the same or smaller rates of growth than (nfor exampleo( also includes the functions ( ) (nlogn)and so on |
13,564 | in the following tablewe list the most common growth rates in order from lowest to highest we sometimes call these growth rates the time complexity of functionor the complexity class of functioncomplexity class name example operations ( constant appendget itemset item (lognlogarithmic finding an element in sorted array (nlinear copyinsertdeleteiteration nlogn linear-logarithmic sort listmerge sort quadratic find the shortest path between two nodes in graph nested loops cubic matrix multiplication exponential 'towers of hanoiproblembacktracking composing complexity classes normallywe need to find the total running time of number of basic operations it turns out that we can combine the complexity classes of simple operations to find the complexity class of more complexcombined operations the goal is to analyze the combined statements in function or method to understand the total time complexity of executing several operations the simplest way to combine two complexity classes is to add them this occurs when we have two sequential operations for exampleconsider the two operations of inserting an element into list and then sorting that list we can see that inserting an item occurs in (ntime and sorting is (nlogntime we can write the total time complexity as ( nlogn)that iswe bring the two functions inside the owe are only interested in the highest order termso this leaves us with just (nlognif we repeat an operationfor examplein while loopthen we multiply the complexity class by the number of times the operation is carried out if an operation with time complexity ( ( )is repeated (ntimes then we multiply the two complexitieso( (no( ) (nf( )for examplesuppose the function fhas time complexity of ( and it is executed times in while loop as followsfor range( ) |
13,565 | the time complexity of this loop then becomes ( (no( ( here we are simply multiplying the time complexity of the operation with the number of times this operation executes the running time of loop is at most the running time of the statements inside the loop multiplied by the number of iterations single nested loopthat isone loop nested inside another loopwill run in time assuming both loops run times for examplefor in range( , )for in range( , #statements each statement is constantcexecuted nn timesso we can express the running time as cn cn ( for consecutive statements within nested loops we add the time complexities of each statement and multiply by the number of times the statement executed for examplen # #executes times for in range( , )print( # #executes times for in range( , )#executes times for in range( , )print( # this can be written as + cn ( we can define (base logarithmic complexityreducing the size of the problem by / in constant time for exampleconsider the following snippeti while <ni= print(inotice that is doubling on each iterationif we run this with we see that it prints out four numbers and if we double we see it prints out five numbers with each subsequent doubling of the number of iterations is only increased by if we assume iterationswe can write this as follows |
13,566 | from this we can conclude that the total time (log( )although big is the most used notation involved in asymptotic analysisthere are two other related notations that should be briefly mentioned they are omega notation and theta notation omega notation (ohmin similar way that big notation describes the upper boundomega notation describes tight lower bound the definition is as followsthe objective is to give the largest rate of growth that is equal to or less than the given algorithmst( )rate of growth theta notation (it is often the case where both the upper and lower bounds of given function are the same and the purpose of theta notation is to determine if this is the case the definition is as followsalthough omega and theta notations are required to completely describe growth ratesthe most practically useful is big notation and this is the one you will see most often |
13,567 | amortized analysis often we are not so interested in the time complexity of individual operationsbut rather the time averaged running time of sequences of operations this is called amortized analysis it is different from average case analysiswhich we will discuss shortlyin that it makes no assumptions regarding the data distribution of input values it doeshowevertake into account the state change of data structures for exampleif list is sorted it should make any subsequent find operations quicker amortized analysis can take into account the state change of data structures because it analyzes sequences of operationsrather then simply aggregating single operations amortized analysis finds an upper bound on runtime by imposing an artificial cost on each operation in sequence of operationsand then combining each of these costs the artificial cost of sequence takes in to account that the initial expensive operations can make subsequent operations cheaper when we have small number of expensive operationssuch as sortingand lots of cheaper operations such as lookupsstandard worst case analysis can lead to overly pessimistic resultssince it assumes that each lookup must compare each element in the list until match is found we should take into account that once we sort the list we can make subsequent find operations cheaper so far in our runtime analysis we have assumed that the input data was completely random and have only looked at the effect the size of the input has on the runtime there are two other common approaches to algorithm analysisthey areaverage case analysis benchmarking average case analysis finds the average running time based on some assumptions regarding the relative frequencies of various input values using real-world dataor data that replicates the distribution of real-world datais many times on particular data distribution and the average running time is calculated benchmarking is simply having an agreed set of typical inputs that are used to measure performance both benchmarking and average time analysis rely on having some domain knowledge we need to know what the typical or expected datasets are ultimately we will try to find ways to improve performance by fine-tuning to very specific application setting |
13,568 | let' look at straightforward way to benchmark an algorithm' runtime performance this can be done by simply timing how long the algorithm takes to complete given various input sizes as we mentioned earlierthis way of measuring runtime performance is dependent on the hardware that it is run on obviously faster processors will give better resultshoweverthe relative growth rates as we increase the input size will retain characteristics of the algorithm itself rather than the hardware it is run on the absolute time values will differ between hardware (and softwareplatformshowevertheir relative growth will still be bound by the time complexity of the algorithm let' take simple example of nested loop it should be fairly obvious that the time complexity of this algorithm is ( since for each iterations in the outer loop there are also iterations in the inter loop for exampleour simple nested for loop consists of simple statement executed on the inner loopdef nest( )for in range( )for in range( ) + the following code is simple test function that runs the nest function with increasing values of with each iteration we calculate the time this function takes to complete using the timeit timeit function the timeit functionin this exampletakes three argumentsa string representation of the function to be timeda setup function that imports the nest functionand an int parameter that indicates the number of times to execute the main statement since we are interested in the time the nest function takes to complete relative to the input sizenit is sufficientfor our purposesto call the nest function once on each iteration the following function returns list of the calculated runtimes for each value of nimport timeit def test ( )ls=[for in range( ) =timeit timeit("nest(str( +")"setup="from __main__ import nest"number ls append(treturn ls in the following code we run the test function and graph the resultstogether with the appropriately scaled function for comparisonrepresented by the dashed lineimport matplotlib pyplot as plt = plt plot(test ( )plt plot([ * / for in range( )] |
13,569 | this gives the following resultsas we can seethis gives us pretty much what we expect it should be remembered that this represents both the performance of the algorithm itself as well as the behavior of underlying software and hardware platformsas indicated by both the variability in the measured runtime and the relative magnitude of the runtime obviously faster processor will result in faster runtimesand also performance will be affected by other running processesmemory constraintsclock speedand so on summary in this we have taken general overview of algorithm design importantlywe saw platform independent way to measure an algorithm' performance we looked at some different approaches to algorithmic problems we looked at way to recursively multiply large numbers and also recursive approach for merge sort we saw how to use backtracking for exhaustive search and generating strings we also introduced the idea of benchmarking and simple platform-dependent way to measure runtime in the following we will revisit many of these ideas with reference to specific data structures in the next we will discuss linked lists and other pointer structures |
13,570 | lists and pointer structures you will have already seen lists in python they are convenient and powerful normallyany time you need to store something in listyou use python' built-in list implementation in this howeverwe are more interested in understanding how lists work so we are going to study list internals as you will noticethere are different types of lists python' list implementation is designed to be powerful and to encompass several different use cases we are going to be bit more strict in our definition of what list is the concept of node is very important to lists we shall discuss them in this but this concept willin different formscome back throughout the rest of the book the focus of this will be the followingunderstand pointers in python treating the concept of nodes implementing singlydoublyand circularly linked lists in this we are going to deal quite bit with pointers so it may be useful to remind ourselves what these are to begin withimagine that you have house that you want to sell lacking timeyou contact an agent to find interested buyers so you pick up your house and take it over to the agentwho will in turn carry the house to anybody who may want to buy it ludicrousyou saynow imagine that you have few python functions that work with images so you pass high-resolution image data between your functions of courseyou don' carry your house around what you would do is write the address of the house down on piece of scrap paper and hand it over to the agent the house remains where it isbut the note containing the directions to the house is passed around you might even write it down on several pieces of paper each one is small enough to fit in your walletbut they all point to the same house |
13,571 | as it turns outthings are not very different in python land those large image files remain in one single place in memory what you do is create variables that hold the locations of those images in memory these variables are small and can easily be passed around between different functions that is the big benefit of pointersthey allow you to point to potentially large segment of memory with just simple memory address support for pointers exists in your computer' hardwarewhere it is known as indirect addressing in pythonyou don' manipulate pointers directlyunlike in some other languagessuch as or pascal this has led some people to think that pointers aren' used in python nothing could be further from the truth consider this assignment in the python interactive shells set(we would normally say that is variable of the type set that iss is set this is not strictly truehowever the variable is rather reference ( "safepointerto set the set constructor creates set somewhere in memory and returns the memory location where that set starts this is what gets stored in python hides this complexity from us we can safely assume that is set and that everything works fine arrays an array is sequential list of data being sequential means that each element is stored right after the previous one in memory if your array is really big and you are low on memoryit could be impossible to find large enough storage to fit your entire array this will lead to problems of coursethe flip side of the coin is that arrays are very fast since each element follows from the previous one in memorythere is no need to jump around between different memory locations this can be very important point to take into consideration when choosing between list and an array in your own real-world applications in the latter parts of python data types and structureswe looked at the array data type and discovered the various operations that could be performed on it |
13,572 | pointer structures contrary to arrayspointer structures are lists of items that can be spread out in memory this is because each item contains one or more links to other items in the structure what type of links these are dependent on the type of structure we have if we are dealing with linked liststhen we will have links to the next (and possibly previousitems in the structure in the case of treewe have parent-child links as well as sibling links in tilebased game where the game map is built up of hexeseach node will have links to up to six adjacent map cells there are several benefits with pointer structures first of allthey don' require sequential storage space secondthey can start small and grow arbitrarily as you add more nodes to the structure as noted in python data types and structureshoweverthis comes at cost if you have list of integerseach node is going to take up the space of an integeras well as an additional integer for storing the pointer to the next node nodes at the heart of lists (and several other data structuresis the concept of node before we go any furtherlet us consider this idea for while to begin withwe shall create few stringsa "eggsb "hamc "spamnow you have three variableseach with unique namea typeand value what we do not have is way of saying in which way the variables relate to each other nodes allow us to do this node is container of datatogether with one or more links to other nodes link is pointer simple type of node is one that only has link to the next node |
13,573 | of courseknowing what we do about pointerswe realize that this is not entirely true the string is not really stored in the nodebut is rather pointer to the actual stringthus the storage requirement for this simple node is two memory addresses the data attribute of the nodes are pointers to the strings eggs and ham finding endpoints we have created three nodesone containing eggsone hamand another spam the eggs node points to the ham nodewhich in turn points to the spam node but what does the spam node point tosince this is the last element in the listwe need to make sure its next member has value that makes this clear if we make the last element point to nothing then we make this fact clear in pythonwe will use the special value none to denote nothingthe last node has its next point pointing to none as such it is the last node in the chain of nodes |
13,574 | node here is simple node implementation of what we have discussed so farclass nodedef __init__(selfdata=none)self data data self next none do not confuse the concept of node with node jsa server-side technology implemented in javascript the next pointer is initialized to nonemeaning that unless you change the value of nextthe node is going to be an end-point this is good ideaso that we do not forget to terminate the list properly you can add other things to the node class as you see fit just make sure that you keep in mind the distinction between node and data if your node is going to contain customer datathen create customer class and put all the data there one thing you may want to do is implement the __str__ method so that it calls the __str__ method of the contained object is called when the node object is passed to printdef __str__(self)return str(dataother node types we have assumed nodes that have pointer to the next node this is probably the simplest type of node howeverdepending on our requirementswe can create number of other types of nodes |
13,575 | sometimes we want to go from to bbut at the same time from to in that casewe add previous pointer in addition to the next pointeras you can see from the figurewe let both the last and the first nodes point to noneto indicate that we have reached they form the boundary of our list end-point the first node' previous pointer points to none since it has no predecessorjust as the last item' next pointer points to none because it no successor node you might also be creating tiles for tile-based game in such caseinstead of previous and nextyou might use northsoutheastand west there are more types of pointersbut the principle is the same tiles at the end of the map will point to none |
13,576 | you can take this as far as you need to if you need to be able to move north-westnortheastsouth-eastand south-west as wellall you have to do is add these pointers to your node class singly linked lists singly linked list is list with only one pointer between two successive nodes it can only be traversed in single directionthat isyou can go from the first node in the list to the last nodebut you cannot move from the last node to the first node we can actually use the node class that we created earlier to implement very simple singly linked listn node('eggs' node('ham' node('spam'next we link the nodes together so that they form chainn next next to traverse the listyou could do something like the following we start by setting the variable current to the first item in the listcurrent while currentprint(current datacurrent current next in the loop we print out the current element after which we set current to point to the next element in the list we keep doing this until we have reached the end of the list there arehoweverseveral problems with this simplistic list implementationit requires too much manual work by the programmer it is too error-prone (this is consequence of the first pointtoo much of the inner workings of the list is exposed to the programmer we are going to address all these issues in the following sections |
13,577 | singly linked list class list is clearly separate concept from node so we start by creating very simple class to hold our list we will start with constructor that holds reference to the very first node in the list since this list is initially emptywe will start by setting this reference to noneclass singlylinkedlistdef __init__(self)self tail none append operation the first operation that we need to perform is to append items to the list this operation is sometimes called an insert operation here we get chance to hide away the node class the user of our list class should really never have to interact with node objects these are purely for internal use first shot at an append(method may look like thisclass singlylinkedlistdef append(selfdata)encapsulate the data in node node node(dataif self tail =noneself tail node elsecurrent self tail while current nextcurrent current next current next node we encapsulate data in nodeso that it now has the next pointer attribute from here we check if there are any existing nodes in the list (that isdoes self tail point to nodeif there is nonewe make the new node the first node of the listotherwisefind the insertion point by traversing the list to the last nodeupdating the next pointer of the last node to the new node |
13,578 | we can append few itemswords singlylinkedlist(words append('egg'words append('ham'words append('spam'list traversal will work more or less like before you will get the first element of the list from the list itselfcurrent words tail while currentprint(current datacurrent current next faster append operation there is big problem with the append method in the previous sectionit has to traverse the entire list to find the insertion point this may not be problem when there are just few items in the listbut wait until you need to add thousands of items each append will be slightly slower than the previous one (ngoes to prove how slow our current implementation of the append method will actually be to fix thiswe will storenot only reference to the first node in the listbut also reference to the last node that waywe can quickly append new node at the end of the list the worst case running time of the append operation is now reduced from (nto ( all we have to do is make sure the previous last node points to the new nodethat is about to be appended to the list here is our updated codeclass singlylinkedlistdef __init__(self)self tail none def append(selfdata)node node(dataif self headself head next node self head node elseself tail node self head node |
13,579 | take note of the convention being used the point at which we append new nodes is through self head the self tail variable points to the first node in the list getting the size of the list we would like to be able to get the size of the list by counting the number of nodes one way we could do this is by traversing the entire list and increasing counter as we go alongdef size(self)count current self tail while currentcount + current current next return count this worksbut list traversal is potentially an expensive operation that we should avoid when we can so insteadwe shall opt for another rewrite of the method we add size member to the singlylinkedlist classinitializing it to in the constructor then we increment size by one in the append methodclass singlylinkedlistdef __init__(self)self size def append(selfdata)self size + because we are now only reading the size attribute of the node objectand not using loop to count the number of nodes in the listwe get to reduce the worst case running time from (nto ( |
13,580 | improving list traversal if you notice how we traverse our list that one place where we are still exposed to the node class we need to use node data to get the contents of the node and node next to get the next node but we mentioned earlier that client code should never need to interact with node objects we can achieve this by creating method that returns generator it looks as followsdef iter(self)current self tail while currentval current data current current next yield val now list traversal is much simpler and looks lot better as well we can completely ignore the fact that there is anything called node outside of the listfor word in words iter()print(wordnotice that since the iter(method yields the data member of the nodeour client code doesn' need to worry about that at all deleting nodes another common operation that you would need to be able to do on list is to delete nodes this may seem simplebut we' first have to decide how to select node for deletion is it going to be by an index number or by the data the node containshere we will choose to delete node by the data it contains |
13,581 | the following is figure of special case considered when deleting node from the listwhen we want to delete node that is between two other nodesall we have to do is make the previous node directly to the successor of its next node that iswe simply cut the node to be deleted out of the chain as in the preceding image |
13,582 | here is the implementation of the delete(method may look likedef delete(selfdata)current self tail prev self tail while currentif current data =dataif current =self tailself tail current next elseprev next current next self size - return prev current current current next it should take (nto delete node list search we may also need way to check whether list contains an item this method is fairly easy to implement thanks to the iter(method we previously wrote each pass of the loop compares the current data to the data being searched for if match is foundtrue is returnedor else false is returneddef search(selfdata)for node in self iter()if data =nodereturn true return false clearing list we may want quick way to clear list fortunately for usthis is very simple all we do is clear the pointers head and tail by setting them to nonedef clear(self)""clear the entire list ""self tail none self head none in one fell swoopwe orphan all the nodes at the tail and head pointers of the list this has ripple effect of orphaning all the nodes in between |
13,583 | doubly linked lists now that we have solid grounding on what singly linked list is and the kind of operations that can be performed on itwe shall now turn our focus one notch higher to the topic of doubly linked lists doubly linked list is somehow similar to singly linked list in that we make use of the same fundamental idea of stringing nodes together in singly linked listthere exists one link between each successive node node in doubly linked list has two pointersa pointer to the next node and pointer to the previous nodea node in singly linked list can only determine the next node associated with it but the referenced node or next node has no way of telling who is doing the referencing the flow of direction is only one way in doubly linked listwe add to each node the ability to not only reference the next node but also the previous node let' examine the nature of the linkages that exist between two successive nodes for better understandingwith the existence of two pointers that point to the next and previous nodesdoubly linked lists become equipped with certain capabilities |
13,584 | doubly linked lists can be traversed in any direction depending on the operation being performeda node within doubly linked list can easily refer to its previous node where necessary without having to designate variable to keep track of that node because singly linked list can only be traversed in one direction it may sometimes mean moving to the start or beginning of the list in order to effect certain changes buried within the list since there is immediate access to both next and previous nodesdeletion operations are much easier to performas you will see later on in this doubly linked list node the python code that creates class to capture what doubly linked list node is includes in its initializing methodthe prevnextand data instance variables when node is newly createdall these variables default to noneclass node(object)def __init__(selfdata=nonenext=noneprev=none)self data data self next next self prev prev the prev variable holds reference to the previous nodewhile the next variable continues to hold reference to the next node doubly linked list it is still important to create class that captures the data that our functions will be operating onclass doublylinkedlist(object)def __init__(self)self head none self tail none self count for the purposes of enhancing the size methodwe also set the count instance variable to head and tail will point to the head and tail of the list when we begin to insert nodes into the list |
13,585 | we adopt new convention where self head points to the beginner node of the list and self tail points to the latest node added to the list this is contrary to the convention we used in the singly linked list there are no fixed rules as to the naming of the head and tail node pointers doubly linked lists also need to provide functions that return the size of the listinserts into the listand also deletes nodes from the list we will be examining some of the code to do this let' commence with the append operation append operation during an append operationit is important to check whether the head is none if it is noneit means that the list is empty and should have the head set pointing to the justcreated node the tail of the list is also pointed at the new node through the head by the end of these series of stepshead and tail will now be pointing to the same nodedef append(selfdata)""append an item to the list ""new_node node(datanonenoneif self head is noneself head new_node self tail self head elsenew_node prev self tail self tail next new_node self tail new_node self count + the following diagram illustrates the head and tail pointers of the doubly linked list when new node is added to an empty list |
13,586 | the else part of the algorithm is only executed if the list is not empty the new node' previous variable is set to the tail of the listnew_node prev self tail the tail' next pointer (or variableis set to the new nodeself tail next new_node lastlywe update the tail pointer to point to the new nodeself tail new_node since an append operation increases the number of nodes by onewe increase the counter by oneself count + |
13,587 | visual representation of the append operation is as followsdelete operation unlike the singly linked listwhere we needed to keep track of the previously encountered node anytime we traversed the whole length of the listthe doubly linked list avoids that whole step this is made possible by the use of the previous pointer the algorithm for removing nodes from doubly linked list caters for basically four scenarios before deletion of node is completed these arewhen the search item is not found at all when the search item is found at the very beginning of the list when the search item is found at the tail end of the list when the search item is found somewhere in the middle of the list the node to be removed is identified when its data instance variable matches the data that is passed to the method to be used in the search for the node if matching node is found and subsequently removedthe variable node_deleted is set to true any other outcome results in node_deleted being set to falsedef delete(selfdata)current self head node_deleted false |
13,588 | in the delete methodthe current variable is set to the head of the list (that isit points to the self head of the lista set of if else statements are then used to search the various parts of the list to find the node with the specified data the head node is searched first since current is pointing at headif current is noneit is presumed that the list has no nodes for search to even begin to find the node to be removedif current is nonenode_deleted false howeverif current (which now points to headcontains the very data being searched forthen self head is set to point to the current next node since there is no node behind head nowself head prev is set to noneelif current data =dataself head current next self head prev none node_deleted true similar strategy is adopted if the node to be removed is located at the tail end of the list this is the third statement that searches for the possibility that the node to be removed might be located at the end of the listelif self tail data =dataself tail self tail prev self tail next none node_deleted true lastlythe algorithm to find and remove node loops through the list of nodes if matching node is foundcurrent' previous node is connected to current' next node after that stepcurrent' next node is connected to previous node of currentelse while currentif current data =datacurrent prev next current next current next prev current prev node_deleted true current current next |
13,589 | the node_delete variable is then checked after all the if-else statements has been evaluated if any of the if-else statements changed this variablethen it means node has been deleted from the list the count variable is therefore decremented by if node_deletedself count - as an example of deleting node that is buried within listassume the existence of three nodesaband to delete node in the middle of the listwe will essentially make point to as its next nodewhile making point to as its previous nodeafter such an operationwe end up with the following list |
13,590 | list search the search algorithm is similar to that of the search method in singly linked list we call the internal method iter(to return the data in all the nodes as we loop through the dataeach is matched against the data passed into the contain method if there is matchwe return trueor else we return false to symbolize that no match was founddef contain(selfdata)for node_data in self iter()if data =node_datareturn true return false our doubly linked list has ( for the append operation and (nfor the delete operation circular lists circular list is special case of linked list it is list where the endpoints are connected that isthe last node in the list points back to the first node circular lists can be based on both singly and doubly linked lists in the case of doubly linked circular listthe first node also needs to point to the last node here we are going to look at an implementation of singly linked circular list it should be straightforward to implement doubly linked circular listonce you have grasped the basic concepts we can reuse the node class that we created in the section on singly linked lists as matter of factwe can reuse most parts of the singlylinkedlist class as well so we are going to focus on the methods where the circular list implementation differs from the normal singly linked list appending elements when we append an element to the circular listwe need to make sure that the new node points back to the tail node this is demonstrated in the following code there is one extra line as compared to the singly linked list implementationdef append(selfdata)node node(dataif self head |
13,591 | self head next node self head node elseself head node self tail node self head next self tail self size + deleting an element we may think that we can follow the same principle as for append and simply make sure the head points to the tail this would give us the following implementationdef delete(selfdata)current self tail prev self tail while currentif current data =dataif current =self tailself tail current next self head next self tail elseprev next current next self size - return prev current current current next as previouslythere is just single line that needs to change it is only when we remove the tail node that we need to make sure that the head node is updated to point to the new tail node howeverthere is serious problem with this code in the case of circular listwe cannot loop until current becomes nonesince that will never happen if you delete an existing nodeyou wouldn' see thisbut try deleting nonexistent node and you will get stuck in an indefinite loop |
13,592 | we thus need to find different way to control the while loop we cannot check whether current has reached headbecause then it will never check the last node but we could use prevsince it lags behind current by one node there is special casehowever the very first loop iterationcurrent and prevwill point to the same nodenamely the tail node we want to ensure that the loop does run heresince we need to take the one node list into consideration the updated delete method now looks as followsdef delete(selfdata)current self tail prev self tail while prev =current or prev !self headif current data =dataif current =self tailself tail current next self head next self tail elseprev next current next self size - return prev current current current next iterating through circular list you do not need to modify the iter(method it will work perfectly well for our circular list but you do need to put in an exit condition when you are iterating through the circular listotherwise your program will get stuck in loop here is way you could do thisby using counter variablewords circularlist(words append('eggs'words append('ham'words append('spam'counter for word in words iter()print(wordcounter + if counter break once we have printed out , elementswe break out of the loop |
13,593 | summary in this we have looked at linked lists we have studied the concepts that underlie listssuch as nodes and pointers to other nodes we implemented the major operations that occur on these types of list and saw how their worst case running times compare in the next we are going to look at two other data structures that are usually implemented using listsstacks and queues |
13,594 | stacks and queues in this we are going to build upon the skills we learned in the last in order to create special list implementations we are still sticking to linear structures we will get to more complex data structures in the coming in this we are going to look at the followingimplementing stacks and queues some applications of stacks and queues stacks stack is data structure that is often likened to stack of plates if you have just washed plateyou put it on top of the stack when you need plateyou take it off the top of the stack so the last plate to be added to the stack will be the first to be removed from the stack thusa stack is last infirst out (lifostructurethe preceding figure depicts stack of plates adding plate to the pile is only possible by leaving that plate on top of the pile to remove plate from the pile of plates means to remove the plate that is on top of the pile |
13,595 | there are two primary operations that are done on stackspush and pop when an element is added to the top of the stackit is pushed onto the stack when an element is taken off the top of the stackit is popped off the stack another operation which is used sometimes is peekwhich makes it possible to see the element on the stack without popping it off stacks are used for number of things one very common usage for stacks is to keep track of the return address during function calls let' imagine that we have the following little programdef ()print(' 'def () ( (print("done"when the program execution gets to the call to ()it first pushes the address of the following instruction onto the stackthen jumps to inside ab(is calledbut before thatthe return address is pushed onto the stack once in (and the function is donethe return address is popped off the stackwhich takes us back to (when has completedthe return address is popped off the stackwhich takes us back to the print statement stacks are actually also used to pass data between functions say you have the following function call somewhere in your codesomefunc( 'eggs''ham''spam'what is going to happen is that 'eggs''hamand 'spamwill be pushed onto the stackone at time |
13,596 | when the code jumps into the functionthe values for abcd will be popped off the stack the spam element will be popped off first and assigned to dthen "hamwill be assigned to cand so ondef somefunc(abcd)print("function executed"stack implementation now let us study an implementation of stack in python we start off by creating node classjust as we did in the previous with listsclass nodedef __init__(selfdata=none)self data data self next none this should be familiar to you by nowa node holds data and reference to the next item in list we are going to implement stack instead of listbut the same principle of nodes linked together still applies now let us look at the stack class it starts off similar to singly linked list we need to know the node at the top of the stack we would also like to keep track of the number of nodes in the stack so we will add these fields to our classclass stackdef __init__(self)self top none self size push operation the push operation is used to add an element to the top of the stack here is an implementationdef push(selfdata)node node(dataif self topnode next self top self top node elseself top node self size + |
13,597 | in the following figurethere is no existing node after creating our new node thus self top will point to this new node the else part of the if statement guarantees that this happensin scenario where we have an existing stackwe move self top so that it points to the newly created node the newly created node must have its next pointerpointing to the node that used to be the top node on the stackpop operation now we need pop method to remove the top element from the stack as we do sowe need to return the topmost element as well we will make the stack return none if there are no more elementsdef pop(self)if self topdata self top data |
13,598 | self size - if self top nextself top self top next elseself top none return data elsereturn none the thing to pay attention to here is the inner if statement if the top node has its next attribute pointing to another nodethen we must set the top of the stack to now point to that nodewhen there is only one node in the stackthe pop operation will proceed as followsremoving such node results in self top pointing to none |
13,599 | peek as we said earlierwe could also add peek method this will just return the top of the stack without removing it from the stackallowing us to look at the top element without changing the stack itself this operation is very straightforward if there is top elementreturn its dataotherwise return none (so that the behavior of peek matches that of pop)def peek(self)if self top return self top data elsereturn none bracket-matching application now let us look at an example of how we can use our stack implementation we are going to write little function that will verify whether statement containing brackets--([or {--is balancedthat iswhether the number of closing brackets matches the number of opening brackets it will also ensure that one pair of brackets really is contained in anotherdef check_brackets(statement)stack stack(for ch in statementif ch in ('{''[''(')stack push(chif ch in ('}'']'')')last stack pop(if last is '{and ch is '}'continue elif last is '[and ch is ']'continue elif last is '(and ch is ')'continue elsereturn false if stack size return false elsereturn true our function parses each character in the statement passed to it if it gets an open bracketit pushes it onto the stack if it gets closing bracketit pops the top element off the stack and compares the two brackets to make sure their types matchshould match )should match ]and should match if they don'twe return falseotherwise we continue parsing |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.