id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
14,300 | python data structures herewe will understand what is data structure with regards to python programming language data structures overview data structures are fundamental concepts of computer sciencewhich helps in writing efficient programs in any language python is high-levelinterpretedinteractive and object-oriented scripting language henceby using python languagewe can study the fundamentals of data structure in simpler way as compared to other programming languages in this we are going to study short overview of some frequently used data structures in general and how they are related to some specific python data types there are also some data structures specific to python which are listed as another category general data structures the various data structures in computer science are divided broadly into two categories as shown below we will discuss about each of the below data structures in detail in subsequent liner data structures these are the data structures which store the data elements in sequential manner arrayit is sequential arrangement of data elements paired with the index of the data element linked listeach data element contains link to another elementalong with the data present in it stackit is data structurewhich follows only to specific order of operation lifo (last in first outor filo(first in last outqueueit is similar to stackbut the order of operation is only fifo (first in first outmatrixit is two dimensional data structure in whichthe data element is referred by pair of indices non-liner data structures these are the data structures in whichthere is no sequential linking of data elements any pair or group of data elements can be linked to each other and can be accessed without strict sequence |
14,301 | binary treeit is data structurewhere each data element can be connected to maximum two other data elements and it starts with root node heapit is special case of tree data structurewhere the data in the parent node is either strictly greater thanequal to the child nodes or strictly less than its child nodes hash tableit is data structurewhich is made of arrays associated with each other using hash function it retrieves values using keys rather thanindex from data element graphit is an arrangement of vertices and nodeswhere some of the nodes are connected to each other through links python specific data structures these data structures are specific to python language and they give greater flexibility in storing different types of data and faster processing in python environment listit is similar to array with the exceptionthat the data elements can be of different data types you can have both numeric and string data in python list tupletuples are similar to listsbut they are immutable which meansthe values in tuple cannot be modified they can only be read dictionarythe dictionary contains key-value pairs as its data elements in the next we are going to learn the details of how each of these data structures can be implemented using python |
14,302 | python data structures python is available on wide variety of platformsincluding linux and mac os let' understandhow to set up our python environment local environment setup open terminal window and type "pythonto find outif it is already installed and which version is installed unix (solarislinuxfreebsdaixhp/uxsunosirixetc win /nt/ macintosh (intelppc kos/ dos (multiple versionspalmos nokia mobile phones windows ce acorn/risc os beos amiga vms/openvms qnx vxworks psion python has also been ported to the java and net virtual machines getting python the most up-to-date and current source codebinariesdocumentationnewsetc is available on the official website of python which is available at you can download python documentation from this website given herewithpostscript formats installing python python distribution is available for wide variety of platforms you need to download only the binary code applicable for your platform and install python |
14,303 | if the binary code for your platform is not availableyou need compiler to compile the source code manually compiling the source code offersmore flexibility in terms of choice of features that you require in your installation here is quick overview of installing python on various platforms unix and linux installation here are the simple steps to install python on unix/linux machine open web browser and go to follow the link to download zipped source code available for unix/linux download and extract files editing the modules/setup fileif you want to customise some options run /configure script make make install this installs python at standard location /usr/local/bin and at /usr/local/lib/pythonxx wherexx is the version of python its libraries windows installation hereare the steps to install python on windows machine open web browser and go to follow the link for the windows installer python-xyz msi file wherexyz is the version you need to install to use this installer python-xyz msithe windows system must support microsoft installer save the installer file to your local machine and thenrun it to find out if your machine supports msi run the downloaded file this brings up the python install wizardwhich is really easy to use just accept the default settingswait until the install is finishedand you are done macintosh installation recent macs come with python installedbut it may be several years out of date see version along with extra tools to support development on the mac for older mac os' before mac os (released in )macpython is available jack jansen maintains it and you can have full access to the entire documentation at his websitewhich is available at can find complete installation details for mac os installation |
14,304 | setting up path programs and other executable files can be in many directoriesso operating systems provide search path thatlists the directories that the os searches for executables the path is stored in an environment variablewhich is named string maintained by the operating system this variable contains information available to the command shell and other programs the path variable is named as path in unix or path in windows (unix is case sensitivewindows is notin mac osthe installer handles the path details to invoke the python interpreter from any particular directoryyou must add the python directory to your path setting path at unix/linux to add the python directory to the path for particular session in unixrefer the followingin the csh shelltype setenv path "$path:/usr/local/bin/pythonand press enter in the bash shell (linux)type export ath="$path:/usr/local/bin/pythonand press enter in the sh or ksh shelltype path="$path:/usr/local/bin/pythonand press enter note/usr/local/bin/python is the path of the python directory setting path at windows to add the python directory to the path for particular session in windowsrefer the followingat the command prompttype path %path%; :\python and press enter notec:\python is the path of the python directory python environment variables here in the table beloware important environment variableswhich can be recognised by python sr no variable description pythonpath it has role similar to path this variable tells the python interpreterwhere to locate the module files imported into program it should include the python source library directory and the directories containing python source code pythonpath is sometimespreset by the python installer |
14,305 | pythonstartup it contains the path of an initialisation file containing python source code it is executed every timeyou start the interpreter it is named as pythonrc py in unix and it contains commands that load utilities or modify pythonpath pythoncaseok it is used in windows to instruct pythonto find the first case-insensitive match in an import statement set this variable to any value to activate it pythonhome it is an alternative module search path it is usually embedded in the pythonstartup or pythonpath directories to make switching module libraries easy running python there are three different ways to start pythonwhich are as followsinteractive interpreter you can start python from unixdosor any other systemthat provides you command line interpreter or shell window enter python the command line start coding right away in the interactive interpreter $python unix/linux or pythonunix/linux or :python windows/dos hereis the list of all the available command line optionswhich is as mentioned belowsr no option description - it provides debug output - it generates optimised bytecode (resulting in pyo files |
14,306 | - do not run import site to look for python paths on startup - verbose output (detailed trace on import statements - disable class-based built-in exceptions (just use strings)obsolete starting with version - cmd run python script sent in as cmd string file run python script from given file script from the command-line python script can be executed at command line by invoking the interpreter on your applicationas in the following$python script py unix/linux or pythonscript py unix/linux or >python script py windows/dos note be sure the file permission mode allows execution integrated development environment (ideyou can run python from graphical user interface (guienvironment as wellif you have gui application on your system that supports python unix idle is the very first unix ide for python windows pythonwin is the first windows interface for python and is an ide with gui |
14,307 | macintosh the macintosh version of pythonalong with the idle ide is available from the main websitedownloadable as either macbinary or binhex' files if you are not able to set up the environment properlythen you can take help from your system admin make sure the python environment is properly set up and working perfectly fine note all the examples given in subsequent are executed with python version available on centos flavor of linux we already have set up python programming environment onlineso thatyou can execute all the available examples online at the same timewhen you are learning theory feel free to modify any example and execute it online |
14,308 | python data structures array is containerwhich can hold fix number of items and these items should be of the same type most of the data structures make use of arrays to implement their algorithms the important terms to understand the concept of array are as followselementeach item stored in an array is called an element index each location of an element in an array has numerical indexwhich is used to identify the element array representation arrays can be declared in various ways in different languages an illustration is given belowas per the above illustrationfollowing are the important points to be consideredindex starts with array length is which means it can store elements each element can be accessed via its index for examplewe can fetch an element at index as basic operations the basic operations supported by an array are as stated belowtraverse print all the array elements one by one insertion adds an element at the given index deletion deletes an element at the given index search searches an elementusing the given index or by the value update updates an element at the given index |
14,309 | array is created in python by importing array module to the python program thenthe array is declared as shown belowfrom array import arrayname array(typecode[initializers]typecode are the codes that are used to define the type of value the array will hold some common typecodes used are as followstypecode value represents signed integer of size byte/tdb represents unsigned integer of size byte represents character of size byte represents signed integer of size bytes represents unsigned integer of size bytes represents floating point of size bytes represents floating point of size bytes before looking at various array operationslets create and print an array using python the below code creates an array named array from array import array array(' '[ , , , , ]for in array print(xoutput when we compile and execute the above programit produces the following result |
14,310 | accessing array element we can access each element of an arrayusing the index of the element the below code shows how to access an array element from array import array array(' '[ , , , , ]print (array [ ]print (array [ ]output when we compile and execute the above programit produces the following resultwhich shows the element is inserted at index position insertion operation insert operation isto insert one or more data elements into an array based on the requirementa new element can be added at the beginningendor any given index of array herewe add data element at the middle of the arrayusing the python in-built insert(method from array import array array(' '[ , , , , ]array insert( , for in array print(xoutput |
14,311 | when we compile and execute the above programit produces the following result which shows the element is inserted at index position deletion operation deletion refers to removing an existing element from the array and re-organising all elements of an array herewe remove data element at the middle of the arrayusing the python in-built remove(method from array import array array(' '[ , , , , ]array remove( for in array print(xoutput when we compile and execute the above programit produces the following resultwhich shows the element is removed from the array search operation you can perform search for an array element based on its value or its index herewe search data elementby using the python in-built index(method from array import |
14,312 | array array(' '[ , , , , ]print (array index( )output when we compile and execute the above programit produces the following result which shows the index of the element if the value is not present in the arraythen the program returns an error update operation update operation refers to updating an existing element from the array at given index herewe simply reassign new value to the desired index we want to update from array import array array(' '[ , , , , ]array [ for in array print(xoutput when we compile and execute the above programit produces the following resultwhich shows the new value at the index position |
14,313 | python data structures the list is most versatile datatype available in pythonwhich can be written as list of comma-separated values (itemsbetween square brackets an important thing about the list is thatitems in list need not be of the same type creating list is as simple as putting different comma-separated values between square brackets for examplelist ['physics''chemistry' list [ list [" "" "" "" "similar to string indiceslist indices start at and lists can be slicedconcatenated and so on accessing values to access values in listsuse the square brackets for slicing along with the index or indices to obtain value available at that index for example#!/usr/bin/python list ['physics''chemistry' list [ print "list [ ]"list [ print "list [ : ]"list [ : when the above code is executedit produces the following resultlist [ ]physics list [ : ][ updating lists you can update single or multiple elements of listsby giving the slice on the left-hand side of the assignment operatorand you can add to elements in list with the append(method for example |
14,314 | #!/usr/bin/python list ['physics''chemistry' print "value available at index print list[ list[ print "new value available at index print list[ note append(method is discussed in subsequent section when the above code is executedit produces the following resultvalue available at index new value available at index delete list elements to remove list elementyou can use either the del statementif you know exactlywhich element(syou are deleting or the remove(methodif you do not know for example#!/usr/bin/python list ['physics''chemistry' print list del list [ print "after deleting value at index print list when the above code is executedit produces following result['physics''chemistry' after deleting value at index ['physics''chemistry' note remove(method is discussed in subsequent section |
14,315 | basic list operations lists respond to the and operators much like stringsthey mean concatenation and repetition here tooexcept that the result is new listnot string in factlists respond to all of the general sequence operations we used on strings in the prior python expression results description len([ ] length [ [ [ concatenation ['hi!' ['hi!''hi!''hi!''hi!'repetition in [ true membership for in [ ]print iteration |
14,316 | python data structures tuple is sequence of immutable python objectsjust like lists the differences between tuples and lists arethe tuples cannot be changed unlike lists and tuples use parentheseswhereas lists use square brackets creating tuple is as simple as putting different comma-separated values optionallyyou can put these comma-separated values between parentheses also for exampletup ('physics''chemistry' )tup ( )tup " "" "" "" "the empty tuple is written as two parentheses containing nothing tup ()to write tuple containing single valueyou have to include comma even thoughthere is only one value tup ( ,)like string indicestuple indices start at and they can be slicedconcatenatedand so on accessing values in tuples to access values in tupleuse the square brackets for slicing along with the index or indices to obtain value available at that index for example#!/usr/bin/python tup ('physics''chemistry' )tup ( )print "tup [ ]"tup [ ]print "tup [ : ]"tup [ : ]when the above code is executedit produces the following resulttup [ ]tup [ : ]physics [ |
14,317 | updating tuples tuples are immutablewhich means you cannot update or change the values of tuple elements you are able to take portions of existing tuplesto create new tuples as the following example demonstrates#!/usr/bin/python tup ( )tup ('abc''xyz')following action is not valid for tuples tup [ so let' create new tuple as follows tup tup tup print tup when the above code is executedit produces the following result( 'abc''xyz'delete tuple elements removing individual tuple elements is not possible there isof coursenothing wrong with putting together another tuple with the undesired elements discarded to explicitly remove an entire tuplejust use the del statement for example#!/usr/bin/python tup ('physics''chemistry' )print tupdel tupprint "after deleting tup "print tupnotean exception raisedbecause after del tuptuple does not exist anymore this produces the following result('physics''chemistry' |
14,318 | after deleting tup traceback (most recent call last)file "test py"line in print tupnameerrorname 'tupis not defined basic tuples operations tuples respond to the and operators much like stringsthey mean concatenation and repetition here tooexcept that the result is new tuplenot string in facttuples respond to all of the general sequence operationswe used on strings in the prior python expression results description len(( ) length ( ( ( concatenation ('hi!', ('hi!''hi!''hi!''hi!'repetition in ( true membership for in ( )print iteration |
14,319 | python data structures in dictionary each key is separated from its value by colon (:)the items are separated by commasand the whole thing is enclosed in curly braces an empty dictionary without any items is written with just two curly braceslike this{keys are unique within dictionary while values may not be the values of dictionary can be of any typebut the keys must be of an immutable data typesuch as stringsnumbersor tuples accessing values in dictionary to access dictionary elementsyou can use the familiar square brackets along with the key to obtain its value simple example is as follows#!/usr/bin/python dict {'name''zara''age' 'class''first'print "dict['name']"dict['name'print "dict['age']"dict['age'when the above code is executedit produces the following resultdict['name']dict['age']zara if we attempt to access data item with keywhich is not part of the dictionarywe get an error as follows#!/usr/bin/python dict {'name''zara''age' 'class''first'print "dict['alice']"dict['alice'when the above code is executedit produces the following resultdict['alice']traceback (most recent call last)file "test py"line in print "dict['alice']"dict['alice']keyerror'alice |
14,320 | updating dictionary you can update dictionary by adding new entry or key-value pairmodifying an existing entryor deleting an existing entry as shown below in the simple example#!/usr/bin/python dict {'name''zara''age' 'class''first'dict['age' update existing entry dict['school'"dps school"add new entry print "dict['age']"dict['age'print "dict['school']"dict['school'when the above code is executedit produces the following resultdict['age'] dict['school']dps school delete dictionary elements you can either remove individual dictionary elements or clear the entire contents of dictionary you can also delete entire dictionary in single operation to explicitly remove an entire dictionaryjust use the del statement simple example is as mentioned below#!/usr/bin/python dict {'name''zara''age' 'class''first'del dict['name']remove entry with key 'namedict clear()remove all entries in dict del dict delete entire dictionary print "dict['age']"dict['age'print "dict['school']"dict['school'note that an exception is raisedbecause after del dict dictionary does not exist anymore this produces the following resultdict['age']traceback (most recent call last) |
14,321 | file "test py"line in print "dict['age']"dict['age']typeerror'typeobject is unsubscriptable note del(method is discussed in subsequent section properties of dictionary keys dictionary values have no restrictions they can be any arbitrary python objecteither standard objects or user-defined objects howeversame is not true for the keys there are two important points to remember about dictionary keys more than one entry per key not allowed which meansno duplicate key is allowed when duplicate keys are encountered during assignmentthe last assignment wins for example#!/usr/bin/python dict {'name''zara''age' 'name''manni'print "dict['name']"dict['name'when the above code is executedit produces the following resultdict['name']manni keys must be immutable which means you can use stringsnumbers or tuples as dictionary keysbut something like ['key'is not allowed an example is as follows#!/usr/bin/python dict {['name']'zara''age' print "dict['name']"dict['name'when the above code is executedit produces the following resulttraceback (most recent call last)file "test py"line in dict {['name']'zara''age' }typeerrorlist objects are unhashable |
14,322 | python data structures two dimensional array is an array within an array it is an array of arrays in this type of arraythe position of data element is referred by two indices instead of one soit represents table with rows and columns of data in the below example of two dimensional arrayobserve that each array element itself is also an array consider an example of recording temperatures four times dayevery day sometimesthe recording instrument may be faulty and we fail to record data such data for four days can be presented as two dimensional array as below day day day day the above data can be represented as two dimensional array as below [[ ][ , ][ ][ , , , ]accessing values the data elements in two dimensional arrays can be accessed using two indices one index referring to the main or parent array and another index referring to the position of the data element in the inner array if we mention only one indexthen the entire inner array is printed for that index position the example below illustrates how it works from array import [[ ][ , ][ ][ , , , ]print( [ ]print( [ ][ ]when the above code is executedit produces the following result[ |
14,323 | to print out the entire two dimensional arraywe can use python for loop as shown below we use end of line to print out the values in different rows from array import [[ ][ , ][ ][ , , , ]for in tfor in rprint( ,end "print(when the above code is executedit produces the following result inserting values we can insert new data elements at specific positionby using the insert(method and specifying the index in an example mentioned belowa new data element is inserted at index position from array import [[ ][ , ][ ][ , , , ] insert( [ , , , , ]for in tfor in rprint( ,end "print(when the above code is executedit produces the following result |
14,324 | updating values we can update the entire inner array or some specific data elements of the inner arrayby reassigning the values using the array index from array import [[ ][ , ][ ][ , , , ] [ [ , [ ][ for in tfor in rprint( ,end "print(when the above code is executedit produces the following result deleting the values we can delete an entire inner array or some specific data elements of the inner arrayby reassigning the values using the del(method with index butin case you need to remove specific data elements in one of the inner arraysthen use the update process described above from array import [[ ][ , ][ ][ , , , ]del [ for in tfor in rprint( ,end "print(when the above code is executedit produces the following result |
14,325 | |
14,326 | python data structures matrix is special case of two dimensional arraywhereeach data element is of strictly same size soevery matrix is also two dimensional array but notvice versa matrices are very important data structures for many mathematical and scientific calculations as we have already discussedtwo dimensional array data structure in the previous we will be focusing on data structure operations specific to matrices in this we will also use the numpy package for matrix data manipulation matrix example consider the case of recording temperature for one week measured in the morningmiddayevening and mid-night it can be presented as matrixusing an array and the reshape method available in numpy from numpy import array([['mon', , , , ],['tue', , , , ]['wed', , , , ],['thu', , , , ]['fri', , , , ],['sat', , , , ]['sun', , , , ]] reshape( ,( , )print(mthe above data can be represented as two dimensional array as below[['mon' ' ' ' '['tue' ' ' ' '['wed' ' ' ' '['thu' ' ' ' '['fri' ' ' ' '['sat' ' ' ' '['sun' ' ' ' ']accessing values the data elements in matrix can be accessed by using the indexes the access methods are sameas the way data is accessed in two dimensional array from numpy import |
14,327 | array([['mon', , , , ],['tue', , , , ]['wed', , , , ],['thu', , , , ]['fri', , , , ],['sat', , , , ]['sun', , , , ]]print data for wednesday print( [ ]print data for friday evening print( [ ][ ]when the above code is executedit produces the following result['wed' adding row use the below mentioned code to add row in matrix from numpy import array([['mon', , , , ],['tue', , , , ]['wed', , , , ],['thu', , , , ]['fri', , , , ],['sat', , , , ]['sun', , , , ]]m_r append( ,[['avg', , , , ]], print(m_rwhen the above code is executedit produces the following result[['mon' ' ' ' '['tue' ' ' ' '['wed' ' ' ' '['thu' ' ' ' '['fri' ' ' ' '['sat' ' ' ' '['sun' ' ' ' '['avg' ' ' ' '] |
14,328 | adding column we can add column to matrix using the insert(method herewe have to mention the indexwhere we want to add the column and an array containing the new values of the columns added in the below examplewe add to new column at the fifth position from the beginning from numpy import array([['mon', , , , ],['tue', , , , ]['wed', , , , ],['thu', , , , ]['fri', , , , ],['sat', , , , ]['sun', , , , ]]m_c insert( ,[ ],[[ ],[ ],[ ],[ ],[ ],[ ],[ ]], print(m_cwhen the above code is executedit produces the following result[['mon' ' ' ' ' '['tue' ' ' ' ' '['wed' ' ' ' ' '['thu' ' ' ' ' '['fri' ' ' ' ' '['sat' ' ' ' ' '['sun' ' ' ' ' ']delete row we can delete row from matrix by using the delete(method we have to specify the index of the row and also the axis valuewhich is for row and for column from numpy import array([['mon', , , , ],['tue', , , , ]['wed', , , , ],['thu', , , , ]['fri', , , , ],['sat', , , , ]['sun', , , , ]] delete( ,[ ], print( |
14,329 | when the above code is executedit produces the following result[['mon' ' ' ' '['tue' ' ' ' '['thu' ' ' ' '['fri' ' ' ' '['sat' ' ' ' '['sun' ' ' ' ']delete column we can delete column from matrix using the delete(method we have to specify the index of the column and also the axis valuewhich is for row and for column from numpy import array([['mon', , , , ],['tue', , , , ]['wed', , , , ],['thu', , , , ]['fri', , , , ],['sat', , , , ]['sun', , , , ]] delete( ,s_[ ], print(mwhen the above code is executedit produces the following result[['mon' ' ' '['tue' ' ' '['wed' ' ' '['thu' ' ' '['fri' ' ' '['sat' ' ' '['sun' ' ' ']update row to update the values in the row of matrixwe simply re-assign the values at the index of the row in the below exampleall the values for thursday' data is marked as zero the index for this row is from numpy import array([['mon', , , , ],['tue', , , , ] |
14,330 | ['wed', , , , ],['thu', , , , ]['fri', , , , ],['sat', , , , ]['sun', , , , ]] [ ['thu', , , , print(mwhen the above code is executedit produces the following result[['mon' ' ' ' '['tue' ' ' ' '['wed' ' ' ' '['thu' ' ' ' '['fri' ' ' ' '['sat' ' ' ' '['sun' ' ' ' '] |
14,331 | python data structures mathematicallya set is collection of items not in any particular order python set is similar to this mathematical definition with below additional conditions the elements in the set cannot be duplicates the elements in the set are immutable (cannot be modified)but the set as whole is mutable there is no index attached to any element in python set so they do not support any indexing or slicing operation set operations the sets in python are typically used for mathematical operations like unionintersectiondifference and complement etc we can create setaccess its elements and carry out these mathematical operations as shown below creating set set is created by using the set(function or placing all the elements within pair of curly braces days=set(["mon","tue","wed","thu","fri","sat","sun"]months={"jan","feb","mar"dates={ , , print(daysprint(monthsprint(dateswhen the above code is executedit produces the following result please notehow the order of the elements has changed in the result set(['wed''sun''fri''tue''mon''thu''sat']set(['jan''mar''feb']set([ ]accessing values in set we cannot access individual values in set we can only access all the elements together as shown above butwe can also get list of individual elementsby looping through the set days=set(["mon","tue","wed","thu","fri","sat","sun"] |
14,332 | for in daysprint(dwhen the above code is executedit produces the following resultwed sun fri tue mon thu sat adding items to set we can add elements to set by using add(method again as discussedthere is no specific index attached to the newly added element days=set(["mon","tue","wed","thu","fri","sat"]days add("sun"print(dayswhen the above code is executedit produces the following resultset(['wed''sun''fri''tue''mon''thu''sat']removing item from set we can remove elements from set by using discard(method again as discussedthere is no specific index attached to the newly added element days=set(["mon","tue","wed","thu","fri","sat"]days discard("sun"print(dayswhen the above code is executedit produces the following result set(['wed''fri''tue''mon''thu''sat'] |
14,333 | union of sets the union operation on two sets produces new set containing all the distinct elements from both the sets in the below examplethe element "wedis present in both the sets daysa set(["mon","tue","wed"]daysb set(["wed","thu","fri","sat","sun"]alldays daysa|daysb print(alldayswhen the above code is executedit produces the following result please note the result has only one "wedset(['wed''fri''tue''mon''thu''sat']intersection of sets the intersection operation on two sets produces new set containing only the common elements from both the sets in the below examplethe element "wedis present in both the sets daysa set(["mon","tue","wed"]daysb set(["wed","thu","fri","sat","sun"]alldays daysa daysb print(alldayswhen the above code is executedit produces the following result please note the result has only one "wedset(['wed']difference of sets the difference operation on two sets produces new set containing only the elements from the first set and none from the second set in the below examplethe element "wedis present in both the sets so it will not be found in the result set daysa set(["mon","tue","wed"]daysb set(["wed","thu","fri","sat","sun"]alldays daysa daysb print(alldayswhen the above code is executedit produces the following result please note the result has only one "wedset(['mon''tue'] |
14,334 | compare sets we can checkif given set is subset or superset of another set the result is true or false depending on the elements present in the sets daysa set(["mon","tue","wed"]daysb set(["mon","tue","wed","thu","fri","sat","sun"]subsetres daysa <daysb supersetres daysb >daysa print(subsetresprint(supersetreswhen the above code is executedit produces the following resulttrue true |
14,335 | python data structures python maps also called chainmap is type of data structure to manage multiple dictionaries together as one unit the combined dictionary contains the key and value pairs in specific sequence eliminating any duplicate keys the best use of chainmap is to search through multiple dictionaries at time and get the proper key-value pair mapping we also see that these chainmaps behave as stack data structure creating chainmap we create two dictionaries and club them using the chainmap method from the collections library thenwe print the keys and values of the result of the combination of the dictionaries if there are duplicate keysthen only the value from the first key is preserved import collections dict {'day ''mon''day ''tue'dict {'day ''wed''day ''thu'res collections chainmap(dict dict creating single dictionary print(res maps,'\ 'print('keys {}format(list(res keys()))print('values {}format(list(res values()))print(print all the elements from the result print('elements:'for keyval in res items()print('{{}format(keyval)print(find specific value in the result print('day in res{}format(('day in res))print('day in res{}format(('day in res))when the above code is executedit produces the following result |
14,336 | [{'day ''mon''day ''tue'}{'day ''thu''day ''wed'}keys ['day ''day ''day 'values ['mon''wed''tue'elementsday mon day wed day tue day in restrue day in resfalse map reordering if we change the order of the dictionaries while clubbing them in the above examplewe see thatthe position of the elements get interchanged as ifthey are in continuous chain this again shows the behaviour of maps as stacks import collections dict {'day ''mon''day ''tue'dict {'day ''wed''day ''thu'res collections chainmap(dict dict print(res maps,'\ 'res collections chainmap(dict dict print(res maps,'\ 'when the above code is executedit produces the following result[{'day ''mon''day ''tue'}{'day ''wed''day ''thu'}[{'day ''wed''day ''thu'}{'day ''mon''day ''tue'} |
14,337 | updating map when the element of the dictionary is updatedthe result is instantly updated in the result of the chainmap in the below examplewe see that the new updated value reflects in the result without explicitly applying the chainmap method again import collections dict {'day ''mon''day ''tue'dict {'day ''wed''day ''thu'res collections chainmap(dict dict print(res maps,'\ 'dict ['day ''friprint(res maps,'\ 'when the above code is executedit produces the following result[{'day ''mon''day ''tue'}{'day ''wed''day ''thu'}[{'day ''mon''day ''tue'}{'day ''wed''day ''fri'} |
14,338 | python data structures linked list is sequence of data elementswhich are connected together via links each data element contains connection to another data element in form of pointer python does not have linked lists in its standard library we implement the concept of linked lists using the concept of nodes as discussed in the previous we have already seenhow we create node class and how to traverse the elements of node in this we are going to study the types of linked lists known as singly linked lists in this type of data structurethere is only one link between any two data elements we create such list and create additional methods to insertupdate and remove elements from the list creation of linked list linked list is created by using the node class we studied in the last we create node object and create another class to use this node object we pass the appropriate values through the node objectto point them to the next data elements the below programcreates the linked list with three data elements in the next sectionwe will see how to traverse the linked list class nodedef __init__(selfdataval=none)self dataval dataval self nextval none class slinkedlistdef __init__(self)self headval none list slinkedlist(list headval node("mon" node("tue" node("wed"link first node to second node list headval nextval link second node to third node nextval |
14,339 | traversing linked list singly linked lists can be traversed in only forward direction starting form the first data element we simply print the value of the next data element by assigning the pointer of the next node to the current data element class nodedef __init__(selfdataval=none)self dataval dataval self nextval none class slinkedlistdef __init__(self)self headval none def listprint(self)printval self headval while printval is not noneprint (printval datavalprintval printval nextval list slinkedlist(list headval node("mon" node("tue" node("wed"link first node to second node list headval nextval link second node to third node nextval list listprint(when the above code is executedit produces the following resultmon tue wed |
14,340 | insertion in linked list inserting element in the linked list involvesreassigning the pointers from the existing nodes to the newly inserted node depending on whether the new data element is getting inserted at the beginning or at the middle or at the end of the linked listwe have the below scenarios inserting at the beginning this involves pointing the next pointer of the new data node to the current head of the linked list sothe current head of the linked list becomes the second data element and the new node becomes the head of the linked list class nodedef __init__(selfdataval=none)self dataval dataval self nextval none class slinkedlistdef __init__(self)self headval none print the linked list def listprint(self)printval self headval while printval is not noneprint (printval datavalprintval printval nextval def atbegining(self,newdata)newnode node(newdataupdate the new nodes next val to existing node newnode nextval self headval self headval newnode list slinkedlist(list headval node("mon" node("tue" node("wed" |
14,341 | list headval nextval nextval list atbegining("sun"list listprint(when the above code is executedit produces the following resultsun mon tue wed inserting at the end this involves pointing the next pointer of the the current last node of the linked list to the new data node so the current last node of the linked list becomes the second last data node and the new node becomes the last node of the linked list class nodedef __init__(selfdataval=none)self dataval dataval self nextval none class slinkedlistdef __init__(self)self headval none function to add newnode def atend(selfnewdata)newnode node(newdataif self headval is noneself headval newnode return laste self headval while(laste nextval)laste laste nextval laste nextval=newnode |
14,342 | print the linked list def listprint(self)printval self headval while printval is not noneprint (printval datavalprintval printval nextval list slinkedlist(list headval node("mon" node("tue" node("wed"list headval nextval nextval list atend("thu"list listprint(when the above code is executedit produces the following resultmon tue wed thu inserting in between two data nodes this involves changing the pointer of specific node to point to the new node that is possible by passing in both the new node and the existing node after whichthe new node will be inserted sowe define an additional class which will change the next pointer of the new node to the next pointer of middle node thenassign the new node to next pointer of the middle node class nodedef __init__(selfdataval=none)self dataval dataval self nextval none class slinkedlist |
14,343 | def __init__(self)self headval none function to add node def inbetween(self,middle_node,newdata)if middle_node is noneprint("the mentioned node is absent"return newnode node(newdatanewnode nextval middle_node nextval middle_node nextval newnode print the linked list def listprint(self)printval self headval while printval is not noneprint (printval datavalprintval printval nextval list slinkedlist(list headval node("mon" node("tue" node("thu"list headval nextval nextval list inbetween(list headval nextval,"fri"list listprint(when the above code is executedit produces the following resultmon tue fri |
14,344 | thu removing an item we can remove an existing node using the key for that node in the below programwe locate the previous node of the node which is to be deleted thenpoint the next pointer of this node to the next node of the node to be deleted class nodedef __init__(selfdata=none)self data data self next none class slinkedlistdef __init__(self)self head none def atbegining(selfdata_in)newnode node(data_innewnode next self head self head newnode function to remove node def removenode(selfremovekey)headval self head if (headval is not none)if (headval data =removekey)self head headval next headval none return while (headval is not none)if headval data =removekeybreak prev headval headval headval next |
14,345 | if (headval =none)return prev next headval next headval none def llistprint(self)printval self head while (printval)print(printval data)printval printval next llist slinkedlist(llist atbegining("mon"llist atbegining("tue"llist atbegining("wed"llist atbegining("thu"llist removenode("tue"llist llistprint(when the above code is executedit produces the following resultthu wed mon |
14,346 | python data structures in the english dictionarythe word stack means arranging objects one over another it is the same waymemory is allocated in this data structure it stores the data elements in similar fashion as bunch of plates are stored one above another in the kitchen sostack data structure allows operations at one endwhich can be called top of the stack we can add elements or remove elements only form this end of the stack in stack the element inserted last in sequencewill come out first as we can remove only from the top of the stack such feature is known as last in first out(lifofeature the operations of adding and removing the elements is known as push and pop in the following programwe implement it as add and remove functions we declare an empty list and use the append(and pop(methodsto add and remove the data elements push into stack let us understandhow to use push in stack refer the program mentioned program belowclass stackdef __init__(self)self stack [def add(selfdataval)use list append method to add element if dataval not in self stackself stack append(datavalreturn true elsereturn false use peek to look at the top of the stack def peek(self)return self stack[- astack stack(astack add("mon"astack add("tue"astack peek( |
14,347 | print(astack peek()astack add("wed"astack add("thu"print(astack peek()when the above code is executedit produces the following resulttue thu pop from stack as we knowwe can remove only the top most data element from the stackwe implement python program which does that the remove function in the following program returns the top most element we check the top element by calculating the size of the stack first and thenuse the in-built pop(method to find out the top most element class stackdef __init__(self)self stack [def add(selfdataval)use list append method to add element if dataval not in self stackself stack append(datavalreturn true elsereturn false use list pop method to remove element def remove(self)if len(self stack< return ("no element in the stack"elsereturn self stack pop(astack stack(astack add("mon"astack add("tue" |
14,348 | astack add("wed"astack add("thu"print(astack remove()print(astack remove()when the above code is executedit produces the following resultthu wed |
14,349 | python data structures we are familiar with queue in our day to day life as we wait for service the queue data structure also means the samewhere the data elements are arranged in queue the uniqueness of queue lies in the way items are added and removed the items are allowed at on endbut removed from the other end soit is first-in-first out method queue can be implemented using python listwhere we can use the insert(and pop(methods to add and remove elements there is no insertion as data elements are always added at the end of the queue adding elements in the below examplewe create queue classwhere we implement the first-in-first-out method we use the in-built insert method for adding data elements class queuedef __init__(self)self queue list(def addtoq(self,dataval)insert method to add element if dataval not in self queueself queue insert( ,datavalreturn true return false def size(self)return len(self queuethequeue queue(thequeue addtoq("mon"thequeue addtoq("tue"thequeue addtoq("wed"print(thequeue size()when the above code is executedit produces the following result |
14,350 | removing element in the below examplewe create queue classwhere we insert the data and then remove the data using the in-built pop method class queuedef __init__(self)self queue list(def addtoq(self,dataval)insert method to add element if dataval not in self queueself queue insert( ,datavalreturn true return false pop method to remove element def removefromq(self)if len(self queue)> return self queue pop(return ("no elements in queue!"thequeue queue(thequeue addtoq("mon"thequeue addtoq("tue"thequeue addtoq("wed"print(thequeue removefromq()print(thequeue removefromq()when the above code is executedit produces the following resultmon tue |
14,351 | python data structures double-ended queueor dequesupports adding and removing elements from either end the more commonly used stacks and queues are degenerate forms of dequeswhere the inputs and outputs are restricted to single end import collections doubleended collections deque(["mon","tue","wed"]doubleended append("thu"print ("appended at right "print (doubleendeddoubleended appendleft("sun"print ("appended at right at left is "print (doubleendeddoubleended pop(print ("deleting from right "print (doubleendeddoubleended popleft(print ("deleting from left "print (doubleendedappended at right deque(['mon''tue''wed''thu']appended at right at left is deque(['sun''mon''tue''wed''thu']deleting from right deque(['sun''mon''tue''wed'] |
14,352 | deleting from left deque(['mon''tue''wed'] |
14,353 | list python data structures we have already seen linked list in earlier in which it is possible only to travel forward in this we see another type of linked list in which it is possible to travel both forward and backward such linked list is called doubly linked list following is the features of doubly linked list doubly linked list contains link element called first and last each link carries data field(sand two link fields called next and prev each link is linked with its next link using its next link each link is linked with its previous link using its previous link the last link carries link as null to mark the end of the list creating doubly linked list we create doubly linked list by using the node class nowwe use the same approach as used in the singly linked list butthe head and next pointers will be used for proper assignation to create two links in each of the nodes in addition to the data present in the node class nodedef __init__(selfdata)self data data self next none self prev none class doubly_linked_listdef __init__(self)self head none adding data elements def push(selfnewval)newnode node(newvalnewnode next self head if self head is not noneself head prev newnode self head newnode |
14,354 | print the doubly linked list def listprint(selfnode)while (node is not none)print(node data)last node node node next dllist doubly_linked_list(dllist push( dllist push( dllist push( dllist listprint(dllist headwhen the above code is executedit produces the following result inserting into doubly linked list herewe are going to see how to insert node to the doubly link list using the following program the program uses method named insertwhich inserts the new node at the third position from the head of the doubly linked list create the node class class nodedef __init__(selfdata)self data data self next none self prev none create the doubly linked list class doubly_linked_listdef __init__(self)self head none define the push method to add elements def push(selfnewval) |
14,355 | newnode node(newvalnewnode next self head if self head is not noneself head prev newnode self head newnode define the insert method to insert the element def insert(selfprev_nodenewval)if prev_node is nonereturn newnode node(newvalnewnode next prev_node next prev_node next newnode newnode prev prev_node if newnode next is not nonenewnode next prev newnode define the method to print the linked list def listprint(selfnode)while (node is not none)print(node data)last node node node next dllist doubly_linked_list(dllist push( dllist push( dllist push( dllist insert(dllist head next dllist listprint(dllist headwhen the above code is executedit produces the following result appending to doubly linked list appending to doubly linked list will add the element at the end |
14,356 | create the node class class nodedef __init__(selfdata)self data data self next none self prev none create the doubly linked list class class doubly_linked_listdef __init__(self)self head none define the push method to add elements at the begining def push(selfnewval)newnode node(newvalnewnode next self head if self head is not noneself head prev newnode self head newnode define the append method to add elements at the end def append(selfnewval)newnode node(newvalnewnode next none if self head is nonenewnode prev none self head newnode return last self head while (last next is not none)last last next last next newnode newnode prev last return define the method to print |
14,357 | def listprint(selfnode)while (node is not none)print(node data)last node node node next dllist doubly_linked_list(dllist push( dllist append( dllist push( dllist push( dllist append( dllist listprint(dllist headwhen the above code is executedit produces the following result please note the position of the elements and for the append operation |
14,358 | python data structures hash tables are type of data structurein which the address or the index value of the data element is generated from hash function that makes accessing the data fasteras the index value behaves as key for the data value in other wordshash table stores key-value pairs but the key is generated through hashing function sothe search and insertion function of data element becomes much faster as the key values themselves become the index of the array which stores the data in pythonthe dictionary data types represent the implementation of hash tables the keys in the dictionary satisfy the following requirements the keys of the dictionary are hashablei they are generated by hashing functionwhich generates unique result for each unique value supplied to the hash function the order of data elements in dictionary is not fixed sowe see the implementation of hash table by using the dictionary data types as below accessing values in dictionary to access dictionary elementsyou can use the familiar square brackets along with the key to obtain its value declare dictionary dict {'name''zara''age' 'class''first'accessing the dictionary with its key print "dict['name']"dict['name'print "dict['age']"dict['age'when the above code is executedit produces the following resultdict['name']dict['age']zara updating dictionary you can update dictionary by adding new entry or key-value pairmodifying an existing entryor deleting an existing entry as shown below in the simple exampledeclare dictionary dict {'name''zara''age' 'class''first' |
14,359 | dict['age' update existing entry dict['school'"dps school"add new entry print "dict['age']"dict['age'print "dict['school']"dict['school'when the above code is executedit produces the following resultdict['age'] dict['school']dps school delete dictionary elements you can either remove individual dictionary elements or clear the entire contents of dictionary you can also delete entire dictionary in single operation to explicitly remove an entire dictionaryjust use the del statement dict {'name''zara''age' 'class''first'del dict['name']remove entry with key 'namedict clear()remove all entries in dict del dict delete entire dictionary print "dict['age']"dict['age'print "dict['school']"dict['school'this produces the following result notethat an exception is raised because after del dict dictionary does not exist anymore dict['age']traceback (most recent call last)file "test py"line in print "dict['age']"dict['age']typeerror'typeobject is unsubscriptable |
14,360 | python data structures tree represents the nodes connected by edges it is non-linear data structure it has the following propertiesone node is marked as root node every node other than the root is associated with one parent node each node can have an arbitrary number of chid node we create tree data structure in python by using the concept of node discussed earlier we designate one node as root node and then add more nodes as child nodes below is program to create the root node create root we just create node class and add assign value to the node this becomes tree with only root node class nodedef __init__(selfdata)self left none self right none self data data def printtree(self)print(self dataroot node( root printtree(when the above code is executedit produces the following result |
14,361 | inserting into tree to insert into treewe use the same node class created above and add an insert class to it the insert class compares the value of the node to the parent node and decides to add it as left node or right node finallythe printtree class is used to print the tree class nodedef __init__(selfdata)self left none self right none self data data def insert(selfdata)compare the new value with the parent node if self dataif data self dataif self left is noneself left node(dataelseself left insert(dataelif data self dataif self right is noneself right node(dataelseself right insert(dataelseself data data print the tree def printtree(self)if self leftself left printtree(printself data)if self rightself right printtree(use the insert method to add nodes |
14,362 | root node( root insert( root insert( root insert( root printtree(when the above code is executedit produces the following result traversing tree the tree can be traversed by deciding on sequence to visit each node as we can clearly see we can start at node then visit the left sub-tree first and right sub-tree next or we can also visit the right sub-tree first and left sub-tree next accordinglythere are different names for these tree traversal methods tree traversal algorithms traversal is process to visit all the nodes of tree and may print their values too becauseall nodes are connected via edges (linkswe always start from the root (headnode that iswe cannot randomly access node in tree there are three ways which we use to traverse tree in-order traversal pre-order traversal post-order traversal in-order traversal in this traversal methodthe left subtree is visited firstthen the root and later the right sub-tree we should always remember that every node may represent subtree itself in the below python programwe use the node class to create place holders for the root node as well as the left and right nodes thenwe create an insert function to add data to the tree finallythe in-order traversal logic is implemented by creating an empty list and adding the left node first followed by the root or parent node at last the left node is added to complete the in-order traversal please note that this process is repeated for each sub-tree until all the nodes are traversed class nodedef __init__(selfdata)self left none |
14,363 | self right none self data data insert node def insert(selfdata)if self dataif data self dataif self left is noneself left node(dataelseself left insert(dataelif data self dataif self right is noneself right node(dataelseself right insert(dataelseself data data print the tree def printtree(self)if self leftself left printtree(printself data)if self rightself right printtree(inorder traversal left -root -right def inordertraversal(selfroot)res [if rootres self inordertraversal(root leftres append(root datares res self inordertraversal(root rightreturn res |
14,364 | root node( root insert( root insert( root insert( root insert( root insert( root insert( print(root inordertraversal(root)when the above code is executedit produces the following result[ pre-order traversal in this traversal methodthe root node is visited firstthen the left subtree and finally the right subtree in the below python programwe use the node class to create place holders for the root node as well as the left and right nodes thenwe create an insert function to add data to the tree finallythe pre-order traversal logic is implemented by creating an empty list and adding the root node first followed by the left node at lastthe right node is added to complete the pre-order traversal please note thatthis process is repeated for each sub-tree until all the nodes are traversed class nodedef __init__(selfdata)self left none self right none self data data insert node def insert(selfdata)if self dataif data self dataif self left is noneself left node(dataelseself left insert(data |
14,365 | elif data self dataif self right is noneself right node(dataelseself right insert(dataelseself data data print the tree def printtree(self)if self leftself left printtree(printself data)if self rightself right printtree(preorder traversal root -left ->right def preordertraversal(selfroot)res [if rootres append(root datares res self preordertraversal(root leftres res self preordertraversal(root rightreturn res root node( root insert( root insert( root insert( root insert( root insert( root insert( print(root preordertraversal(root)when the above code is executedit produces the following result |
14,366 | [ post-order traversal in this traversal methodthe root node is visited lasthence the name firstwe traverse the left subtreethen the right subtree and finally the root node in the below python programwe use the node class to create place holders for the root node as well as the left and right nodes thenwe create an insert function to add data to the tree finallythe post-order traversal logic is implemented by creating an empty list and adding the left node first followed by the right node at last the root or parent node is added to complete the post-order traversal please note thatthis process is repeated for each sub-tree until all the nodes are traversed class nodedef __init__(selfdata)self left none self right none self data data insert node def insert(selfdata)if self dataif data self dataif self left is noneself left node(dataelseself left insert(dataelif data self dataif self right is noneself right node(dataelseself right insert(dataelseself data data print the tree |
14,367 | def printtree(self)if self leftself left printtree(printself data)if self rightself right printtree(postorder traversal left ->right -root def postordertraversal(selfroot)res [if rootres self postordertraversal(root leftres res self postordertraversal(root rightres append(root datareturn res root node( root insert( root insert( root insert( root insert( root insert( root insert( print(root postordertraversal(root)when the above code is executedit produces the following result[ |
14,368 | python data structures binary search tree (bstis treein which all the nodes follow the below-mentioned properties the left sub-tree of node has key less than or equal to its parent node' key the right sub-tree of node has key greater than to its parent node' key thusbst divides all its sub-trees into two segmentsthe left sub-tree and the right sub-tree left_subtree (keys<node (key<right_subtree (keyssearch for value in -tree searching for value in tree involves comparing the incoming value with the value exiting nodes here alsowe traverse the nodes from left to right and then finallywith the parent if the searched for value does not match any of the existing valuethen we return not found messageor else the found message is returned class nodedef __init__(selfdata)self left none self right none self data data insert method to create nodes def insert(selfdata)if self dataif data self dataif self left is noneself left node(dataelseself left insert(dataelif data self dataif self right is noneself right node(dataelseself right insert(data |
14,369 | elseself data data findval method to compare the value with nodes def findval(selflkpval)if lkpval self dataif self left is nonereturn str(lkpval)+not foundreturn self left findval(lkpvalelif lkpval self dataif self right is nonereturn str(lkpval)+not foundreturn self right findval(lkpvalelseprint(str(self datais found'print the tree def printtree(self)if self leftself left printtree(printself data)if self rightself right printtree(root node( root insert( root insert( root insert( print(root findval( )print(root findval( )when the above code is executedit produces the following result not found is found |
14,370 | python data structures heap is special tree structure in which each parent node is less than or equal to its child node thenit is called min heap if each parent node is greater than or equal to its child nodethen it is called max heap it is very useful is implementing priority queueswhere the queue item with higher weightage is given more priority in processing detailed discussion on heaps is available in our website here please study it firstif you are new to head data structure in this we will see the implementation of heap data structure using python create heap heap is created by using python' inbuilt library named heapq this library has the relevant functions to carry out various operations on heap data structure belowis list of these functions heapify this function converts regular list to heap in the resulting heap the smallest element gets pushed to the index position but rest of the data elements are not necessarily sorted heappush this function adds an element to the heap without altering the current heap heappop this function returns the smallest data element from the heap heapreplace this function replaces the smallest data element with new value supplied in the function creating heap heap is created by simply using list of elements with the heapify function in the below examplewe supply list of elements and the heapify function rearranges the elements bringing the smallest element to the first position import heapq [ , , , , , use heapify to rearrange the elements heapq heapify(hprint(hwhen the above code is executedit produces the following result[ |
14,371 | inserting into heap inserting data element to heap always adds the element at the last index butyou can apply heapify function again to bring the newly added element to the first index only if it smallest in value in the below example we insert the number import heapq [ , , , , , covert to heap heapq heapify(hprint(hadd element heapq heappush( , print(hwhen the above code is executedit produces the following result[ [ removing from heap you can remove the element at first index by using this function in the below examplethe function will always remove the element at the index position import heapq [ , , , , , create the heap heapq heapify(hprint(hremove element from the heap heapq heappop(hprint(hwhen the above code is executedit produces the following result[ [ |
14,372 | replacing in heap the heapreplace function always removes the smallest element of the heap and inserts the new incoming element at some place not fixed by any order import heapq [ , , , , , create the heap heapq heapify(hprint(hreplace an element heapq heapreplace( , print( [ [ |
14,373 | python data structures graph is pictorial representation of set of objects where some pairs of objects are connected by links the interconnected objects are represented by points termed as verticesand the links that connect the vertices are called edges the various terms and functionalities associated with graph is described in great detail in our tutorial here in this we are going to see how to create graph and add various data elements to it using python program following are the basic operations we perform on graphs display graph vertices display graph edges add vertex add an edge creating graph graph can be easily presented using the python dictionary data types we represent the vertices as the keys of the dictionary and the connection between the vertices also called edges as the values in the dictionary take look at the following graphin the above graphv {abcdee {abacbdcddewe can present this graph in python program as belowcreate the dictionary with graph elements graph " [" "," "]" [" "" "]" [" "" "]" [" "]" [" " |
14,374 | print the graph print(graphwhen the above code is executedit produces the following result{' '[' '' ']' '[' '' ']' '[' ']' '[' ']' '[' '' ']display graph vertices to display the graph verticeswe simple find the keys of the graph dictionary we use the keys(method class graphdef __init__(self,gdict=none)if gdict is nonegdict [self gdict gdict get the keys of the dictionary def getvertices(self)return list(self gdict keys()create the dictionary with graph elements graph_elements " [" "," "]" [" "" "]" [" "" "]" [" "]" [" " graph(graph_elementsprint( getvertices()when the above code is executedit produces the following result[' '' '' '' '' ' |
14,375 | display graph edges finding the graph edges is little trickier than the vertices as we have to find each of the pairs of vertices which have an edge in between them sowe create an empty list of edges then iterate through the edge values associated with each of the vertices list is formed containing the distinct group of edges found from the vertices class graphdef __init__(self,gdict=none)if gdict is nonegdict {self gdict gdict def edges(self)return self findedges(find the distinct list of edges def findedges(self)edgename [for vrtx in self gdictfor nxtvrtx in self gdict[vrtx]if {nxtvrtxvrtxnot in edgenameedgename append({vrtxnxtvrtx}return edgename create the dictionary with graph elements graph_elements " [" "," "]" [" "" "]" [" "" "]" [" "]" [" " graph(graph_elementsprint( edges()when the above code is executedit produces the following result |
14,376 | [{' '' '}{' '' '}{' '' '}{' '' '}{' '' '}adding vertex adding vertex is straight forwardwhere we add another additional key to the graph dictionary class graphdef __init__(self,gdict=none)if gdict is nonegdict {self gdict gdict def getvertices(self)return list(self gdict keys()add the vertex as key def addvertex(selfvrtx)if vrtx not in self gdictself gdict[vrtx[create the dictionary with graph elements graph_elements " [" "," "]" [" "" "]" [" "" "]" [" "]" [" " graph(graph_elementsg addvertex(" "print( getvertices()when the above code is executedit produces the following result[' '' '' '' '' ',' ' |
14,377 | adding an edge adding an edge to an existing graph involves treating the new vertex as tuple and validating if the edge is already present if notthen the edge is added class graphdef __init__(self,gdict=none)if gdict is nonegdict {self gdict gdict def edges(self)return self findedges(add the new edge def addedge(selfedge)edge set(edge(vrtx vrtx tuple(edgeif vrtx in self gdictself gdict[vrtx append(vrtx elseself gdict[vrtx [vrtx list the edge names def findedges(self)edgename [for vrtx in self gdictfor nxtvrtx in self gdict[vrtx]if {nxtvrtxvrtxnot in edgenameedgename append({vrtxnxtvrtx}return edgename create the dictionary with graph elements graph_elements " [" "," "]" [" "" "]" [" "" "]" [" "] |
14,378 | " [" " graph(graph_elementsg addedge({' ',' '} addedge({' ',' '}print( edges()when the above code is executedit produces the following result[{' '' '}{' '' '}{' '' '}{' '' '}{' '' '}{' '' '} |
14,379 | python data structures algorithm is step-by-step procedurewhich defines set of instructions to be executed in certain order to get the desired output algorithms are generally created independent of underlying languagesi an algorithm can be implemented in more than one programming language from the data structure point of viewfollowing are some important categories of algorithmssearch algorithm to search an item in data structure sort algorithm to sort items in certain order insert algorithm to insert item in data structure update algorithm to update an existing item in data structure delete algorithm to delete an existing item from data structure characteristics of an algorithm not all procedures can be called an algorithm an algorithm should have the following characteristicsunambiguous algorithm should be clear and unambiguous each of its steps (or phases)and their inputs/outputs should be clear and must lead to only one meaning input an algorithm should have or more well-defined inputs output an algorithm should have or more well-defined outputsand should match the desired output finiteness algorithms must terminate after finite number of steps feasibility should be feasible with the available resources independent an algorithm should have step-by-step directionswhich should be independent of any programming code how to write an algorithmthere are no well-defined standards for writing algorithms ratherit is problem and resource dependent algorithms are never written to support particular programming code as we know that all programming languages share basic code constructs like loops (doforwhile)flow-control (if-else)etc these common constructs can be used to write an algorithm |
14,380 | we write algorithms in step-by-step mannerbut it is not always the case algorithm writing is process and is executed after the problem domain is well-defined that iswe should know the problem domainfor which we are designing solution example let' try to learn algorithm-writing by using an example problem design an algorithm to add two numbers and display the result step start step declare three integers ab step define values of step add values of step store output of step to step print step stop algorithms tell the programmers how to code the program alternativelythe algorithm can be written asstep start add step get values of step step display step stop in design and analysis of algorithmsusually the second method is used to describe an algorithm it makes it easy for the analyst to analyse the algorithm ignoring all unwanted definitions he can observe what operations are being used and how the process is flowing writing step numbersis optional we design an algorithm to get solution of given problem problem can be solved in more than one ways |
14,381 | hencemany solution algorithms can be derived for given problem the next step is to analyse those proposed solution algorithms and implement the best suitable solution |
14,382 | python data structures in divide and conquer approachthe problem in handis divided into smaller sub-problems and then each problem is solved independently whenwe keep on dividing the sub problems into even smaller sub-problemswe may eventually reach stage where no more division is possible those "atomicsmallest possible sub-problem (fractionsare solved the solution of all sub-problems is finally merged in order to obtain the solution of an original problem broadlywe can understand divide-and-conquer approach in three-step process divide/break this step involves breaking the problem into smaller sub-problems sub-problems should represent part of the original problem this step generally takes recursive approach to divide the problem until no sub-problem is further divisible at this stagesub-problems become atomic in nature but still represent some part of the actual problem conquer/solve this step receives lot of smaller sub-problems to be solved generallyat this levelthe problems are considered 'solvedon their own merge/combine when the smaller sub-problems are solvedthis stage recursively combines them until they formulate solution of the original problem this algorithmic approach works recursively and conquer merge steps works so close that they appear as one |
14,383 | examples the following program is an example of divide-and-conquer programming approach where the binary search is implemented using python binary search implementation in binary searchwe take sorted list of elements and start looking for an element at the middle of the list if the search value matches with the middle value in the listwe complete the search otherwisewe eliminate half of the list of elements by choosing whether to process with the right or left half of the list depending on the value of the item searched this is possible as the list is sorted and it is much quicker than linear search herewe divide the given list and conquer by choosing the proper half of the list we repeat this approach till we find the element or conclude about its absence in the list def bsearch(listval)list_size len(list idx idxn list_size find the middle most value while idx <idxnmidval (idx idxn)/ if list[midval=valreturn midval compare the value the middle most value if val list[midval]idx midval elseidxn midval if idx idxnreturn none initialize the sorted list list [ , , , , , print the search result |
14,384 | print(bsearch(list, )print(bsearch(list, )when the above code is executedit produces the following result none |
14,385 | python data structures recursion allows function to call itself fixed steps of code get executed again and again for new values we also have to set criteria for deciding when the recursive call ends in the below example we see recursive approach to the binary search we take sorted list and give its index range as input to the recursive function binary search using recursion we implement the algorithm of binary search using python as shown below we use an ordered list of items and design recursive function to take in the list along with starting and ending index as input thenthe binary search function calls itself till find the searched item or concludes about its absence in the list def bsearch(listidx idxnval)if (idxn idx )return none elsemidval idx ((idxn idx / compare the search item with middle most value if list[midvalvalreturn bsearch(listidx midval- ,valelif list[midvalvalreturn bsearch(listmidval+ idxnvalelsereturn midval list [ , , , , , print(bsearch(list )print(bsearch(list )when the above code is executedit produces the following result none |
14,386 | python data structures backtracking is form of recursion butit involves choosing only option out of any possibilities we begin by choosing an option and backtrack from itif we reach state where we conclude that this specific option does not give the required solution we repeat these steps by going across each available option until we get the desired solution below is an example of finding all possible order of arrangements of given set of letters when we choose pair we apply backtracking to verify if that exact pair has already been created or not if not already createdthe pair is added to the answer list else it is ignored def permute(lists)if list = return elsereturn for in permute( sfor in permute(list sprint(permute( [" "," "," "])print(permute( [" "," "," "])when the above code is executedit produces the following result[' '' '' '['aa''ab''ac''ba''bb''bc''ca''cb''cc' |
14,387 | python data structures sorting refers to arranging data in particular format sorting algorithm specifies the way to arrange data in particular order most common orders are in numerical or lexicographical order the importance of sorting lies in the fact that data searching can be optimized to very high levelif data is stored in sorted manner sorting is also used to represent data in more readable formats below we see five such implementations of sorting in python bubble sort merge sort insertion sort shell sort selection sort bubble sort it is comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order def bubblesort(list)swap the elements to arrange in order for iter_num in range(len(list)- , ,- )for idx in range(iter_num)if list[idx]>list[idx+ ]temp list[idxlist[idxlist[idx+ list[idx+ temp list [ , , , , , , , bubblesort(listprint(listwhen the above code is executedit produces the following result[ |
14,388 | merge sort merge sort first divides the array into equal halves and then combines them in sorted manner def merge_sort(unsorted_list)if len(unsorted_list< return unsorted_list find the middle point and devide it middle len(unsorted_list/ left_list unsorted_list[:middleright_list unsorted_list[middle:left_list merge_sort(left_listright_list merge_sort(right_listreturn list(merge(left_listright_list)merge the sorted halves def merge(left_half,right_half)res [while len(left_half! and len(right_half! if left_half[ right_half[ ]res append(left_half[ ]left_half remove(left_half[ ]elseres append(right_half[ ]right_half remove(right_half[ ]if len(left_half= res res right_half elseres res left_half return res unsorted_list [ print(merge_sort(unsorted_list) |
14,389 | when the above code is executedit produces the following result[ insertion sort insertion sort involves finding the right place for given element in sorted list so in beginning we compare the first two elements and sort them by comparing them thenwe pick the third element and find its proper position among the previous two sorted elements this waywe gradually go on adding more elements to the already sorted list by putting them in their proper position def insertion_sort(inputlist)for in range( len(inputlist)) - nxt_element inputlist[icompare the current element with next one while (inputlist[jnxt_elementand ( > )inputlist[ + inputlist[jj= - inputlist[ + nxt_element list [ , , , , , , , insertion_sort(listprint(listwhen the above code is executedit produces the following result[ shell sort shell sort involves sorting elementswhich are away from each other we sort large sublist of given list and go on reducing the size of the list until all elements are sorted the below program finds the gap by equating it to half of the length of the list size and then starts sorting all elements in it thenwe keep resetting the gap until the entire list is sorted def shellsort(input_list)gap len(input_list/ while gap |
14,390 | for in range(gaplen(input_list))temp input_list[ij sort the sub list for this gap while >gap and input_list[ gaptempinput_list[jinput_list[ gapj -gap input_list[jtemp reduce the gap for the next element gap gap// list [ , , , , , , , shellsort(listprint(listwhen the above code is executedit produces the following result[ selection sort in selection sort we start by finding the minimum value in given list and move it to sorted list thenwe repeat the process for each of the remaining elements in the unsorted list the next element entering the sorted list is compared with the existing elements and placed at its correct position soat the end all the elements from the unsorted list are sorted def selection_sort(input_list)for idx in range(len(input_list))min_idx idx for in rangeidx + len(input_list))if input_list[min_idxinput_list[ ]min_idx |
14,391 | swap the minimum value with the compared value input_list[idx]input_list[min_idxinput_list[min_idx]input_list[idxl [ , , , , , , , selection_sort(lprint(lwhen the above code is executedit produces the following result[ |
14,392 | algorithms python data structures searching is very basic necessity when you store data in different data structures the simplest approach is to go across every element in the data structure and match it with the value you are searching for this is known as linear search it is inefficient and rarely usedbut creating program for it gives an idea about how we can implement some advanced search algorithms linear search in this type of searcha sequential search is made over all items one by one every item is checked and if match is found then that particular item is returnedotherwise the search continues till the end of the data structure def linear_search(valuessearch_for)search_at search_res false match the value with each data element while search_at len(valuesand search_res is falseif values[search_at=search_forsearch_res true elsesearch_at search_at return search_res [ print(linear_search( )print(linear_search( )when the above code is executedit produces the following resulttrue false interpolation search this search algorithm works on the probing position of the required value for this algorithm to work properlythe data collection should be in sorted form and equally distributed initiallythe probe position is the position of the middle most item of the |
14,393 | collection if match occursthen the index of the item is returned if the middle item is greater than the itemthen the probe position is again calculated in the sub-array to the right of the middle item otherwisethe item is searched in the subarray to the left of the middle item this process continues on the sub-array as well until the size of subarray reduces to zero there is specific formula to calculate the middle positionwhich is indicated in the program belowdef intpolsearch(values, )idx idxn (len(values while idx values[idx and <values[idxn]find the mid point mid idx +int(((float(idxn idx )/values[idxnvalues[idx ]) values[idx ]))compare the value at mid point with search value if values[mid=xreturn "found "+str( )+at index "+str(midif values[midxidx mid return "searched element not in the listl [ print(intpolsearch( )when the above code is executedit produces the following resultfound at index |
14,394 | python data structures graphs are very useful data structures in solving many important mathematical challenges for examplecomputer network topology or analysing molecular structures of chemical compounds they are also used in city traffic or route planning and even in human languages and their grammar all these applications have common challenge of traversing the graph using their edges and ensuring that all nodes of the graphs are visited there are two common established methods to do this traversal which is described below depth first traversal also called depth first search (dfs)this algorithm traverses graph in depth ward motion and uses stack to remember to get the next vertex to start searchwhen dead end occurs in any iteration we implement dfs for graph in python using the set data types as they provide the required functionalities to keep track of visited and unvisited nodes class graphdef __init__(self,gdict=none)if gdict is nonegdict {self gdict gdict check for the visisted and unvisited nodes def dfs(graphstartvisited none)if visited is nonevisited set(visited add(startprint(startfor next in graph[startvisiteddfs(graphnextvisitedreturn visited gdict "aset([" "," "])"bset([" "" "])"cset([" "" "])"dset([" "])"eset([" "] |
14,395 | dfs(gdict' 'when the above code is executedit produces the following resulta breadth first traversal also called breadth first search (bfs)this algorithm traverses graph breadth ward motion and uses queue to remember to get the next vertex to start searchwhen dead end occurs in any iteration please visit this link in our website to understand the details of bfs steps for graph we implement bfs for graph in python using queue data structure discussed earlier when we keep visiting the adjacent unvisited nodes and keep adding it to the queue then we start deque only the node which is left with no unvisited nodes we stop the program when there is no next adjacent node to be visited import collections class graphdef __init__(self,gdict=none)if gdict is nonegdict {self gdict gdict def bfs(graphstartnode)track the visited and unvisited nodes using queue seenqueue set([startnode])collections deque([startnode]while queuevertex queue popleft(marked(vertexfor node in graph[vertex]if node not in seenseen add(nodequeue append(nodedef marked( )print( |
14,396 | the graph dictionary gdict "aset([" "," "])"bset([" "" "])"cset([" "" "])"dset([" "])"eset([" "]bfs(gdict" "when the above code is executedit produces the following resulta |
14,397 | python data structures efficiency of an algorithm can be analysed at two different stagesbefore implementation and after implementation they are as followsa priori analysis this is theoretical analysis of an algorithm efficiency of an algorithm is measured by assuming that all other factorsfor exampleprocessor speedare constant and have no effect on the implementation posterior analysis this is an empirical analysis of an algorithm the selected algorithm is implemented using programming language this is then executed on target computer machine in this analysisactual statistics like running time and space requiredare collected algorithm complexity suppose is an algorithm and is the size of input datathe time and space used by the algorithm are the two main factorswhich decide the efficiency of time factor time is measured by counting the number of key operations such as comparisons in the sorting algorithm space factor space is measured by counting the maximum memory space required by the algorithm the complexity of an algorithm (ngives the running time and/or the storage space required by the algorithm in terms of as the size of input data space complexity space complexity of an algorithm represents the amount of memory space required by the algorithm in its life cycle the space required by an algorithm is equal to the sum of the following two componentsa fixed part that is space required to store certain data and variablesthat are independent of the size of the problem for examplesimple variables and constants usedprogram sizeetc variable part is space required by variableswhose size depends on the size of the problem for exampledynamic memory allocationrecursion stack spaceetc space complexity (pof any algorithm is (pc sp( )where is the fixed part and (iis the variable part of the algorithmwhich depends on instance characteristic following is simple example that tries to explain the concept algorithmsum(ab |
14,398 | step start step step stop herewe have three variables aband and one constant hence ( nowspace depends on data types of given variables and constant types and it will be multiplied accordingly time complexity time complexity of an algorithm represents the amount of time required by the algorithm to run to completion time requirements can be defined as numerical function ( )where (ncan be measured as the number of stepsprovided each step consumes constant time for exampleaddition of two -bit integers takes steps consequentlythe total computational time is (nc nwhere is the time taken for the addition of two bits herewe observe that (ngrows linearly as the input size increases |
14,399 | python data structures the efficiency and accuracy of algorithms have to be analysed to compare them and choose specific algorithm for certain scenarios the process of making this analysis is called asymptotic analysis it refers to computing the running time of any operation in mathematical units of computation for examplethe running time of one operation is computed as (nand may be for another operation it is computed as ( this means the first operation running time will increase linearly with the increase in and the running time of the second operation will increase exponentially when increases similarlythe running time of both operations will be nearly the same if is significantly small usuallythe time required by an algorithm falls under three typesbest case minimum time required for program execution average case average time required for program execution worst case maximum time required for program execution asymptotic notations the commonly used asymptotic notations to calculate the running time complexity of an algorithm are as followso notation notation th notation big oh notationo the notation (nis the formal way to express the upper bound of an algorithm' running time it measures the worst case time complexity or the longest amount of time an algorithm can possibly take to complete for examplefor function ( |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.