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 s... |
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 tablei... |
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/uxsunosir... |
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 he... |
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 a... |
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-i... |
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 ... |
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 perfect... |
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 elemen... |
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 represen... |
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... |
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 ... |
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... |
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 be... |
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... |
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 [ [ [ ... |
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 ... |
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 tu... |
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 th... |
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... |
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... |
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 tr... |
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 i... |
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... |
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 ... |
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 a... |
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 ma... |
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',... |
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 fr... |
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 ther... |
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"pri... |
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 ... |
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 ... |
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 ... |
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 ift... |
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 ... |
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 discusse... |
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 no... |
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 b... |
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 be... |
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 res... |
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 printv... |
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 s... |
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 c... |
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 o... |
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 return... |
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... |
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 ... |
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("... |
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 doub... |
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 g... |
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... |
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 hea... |
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 ... |
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 throu... |
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 c... |
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... |
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... |
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 w... |
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 pri... |
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 ... |
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 dat... |
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 ins... |
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( roo... |
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 le... |
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... |
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 wei... |
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(had... |
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 des... |
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 noneg... |
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 o... |
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(selfvr... |
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(selfed... |
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 ... |
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 algo... |
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 possibl... |
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 ... |
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... |
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... |
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 s... |
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_sor... |
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... |
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 resul... |
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 pr... |
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... |
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 applic... |
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 o... |
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... |
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 tim... |
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 exa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.