Python – Maps

Python – Maps ”; Previous Next Python Maps also called ChainMap is a type of data structure to manage multiple dictionaries together as one unit. The combined dictionary contains the key and value pairs in a specific sequence eliminating any duplicate keys. The best use of ChainMap is to search through multiple dictionaries at a time and get the proper key-value pair mapping. We also see that these ChainMaps behave as stack data structure. Creating a ChainMap We create two dictionaries and club them using the ChainMap method from the collections library. Then we print the keys and values of the result of the combination of the dictionaries. If there are duplicate keys, then only the value from the first key is preserved. Example import collections dict1 = {”day1”: ”Mon”, ”day2”: ”Tue”} dict2 = {”day3”: ”Wed”, ”day1”: ”Thu”} res = collections.ChainMap(dict1, dict2) # Creating a single dictionary print(res.maps,”n”) print(”Keys = {}”.format(list(res.keys()))) print(”Values = {}”.format(list(res.values()))) print() # Print all the elements from the result print(”elements:”) for key, val in res.items(): print(”{} = {}”.format(key, val)) print() # Find a specific value in the result print(”day3 in res: {}”.format((”day1” in res))) print(”day4 in res: {}”.format((”day4” in res))) Output When the above code is executed, it produces the following result − [{”day1”: ”Mon”, ”day2”: ”Tue”}, {”day1”: ”Thu”, ”day3”: ”Wed”}] Keys = [”day1”, ”day3”, ”day2”] Values = [”Mon”, ”Wed”, ”Tue”] elements: day1 = Mon day3 = Wed day2 = Tue day3 in res: True day4 in res: False Map Reordering If we change the order the dictionaries while clubbing them in the above example we see that the position of the elements get interchanged as if they are in a continuous chain. This again shows the behavior of Maps as stacks. Example import collections dict1 = {”day1”: ”Mon”, ”day2”: ”Tue”} dict2 = {”day3”: ”Wed”, ”day4”: ”Thu”} res1 = collections.ChainMap(dict1, dict2) print(res1.maps,”n”) res2 = collections.ChainMap(dict2, dict1) print(res2.maps,”n”) Output When the above code is executed, it produces the following result − [{”day1”: ”Mon”, ”day2”: ”Tue”}, {”day3”: ”Wed”, ”day4”: ”Thu”}] [{”day3”: ”Wed”, ”day4”: ”Thu”}, {”day1”: ”Mon”, ”day2”: ”Tue”}] Updating Map When the element of the dictionary is updated, the result is instantly updated in the result of the ChainMap. In the below example we see that the new updated value reflects in the result without explicitly applying the ChainMap method again. Example import collections dict1 = {”day1”: ”Mon”, ”day2”: ”Tue”} dict2 = {”day3”: ”Wed”, ”day4”: ”Thu”} res = collections.ChainMap(dict1, dict2) print(res.maps,”n”) dict2[”day4”] = ”Fri” print(res.maps,”n”) Output When the above code is executed, it produces the following result − [{”day1”: ”Mon”, ”day2”: ”Tue”}, {”day3”: ”Wed”, ”day4”: ”Thu”}] [{”day1”: ”Mon”, ”day2”: ”Tue”}, {”day3”: ”Wed”, ”day4”: ”Fri”}] Print Page Previous Next Advertisements ”;

Python – Stack

Python – Stack ”; Previous Next In the english dictionary the word stack means arranging objects on over another. It is the same way memory is allocated in this data structure. It stores the data elements in a similar fashion as a bunch of plates are stored one above another in the kitchen. So stack data strcuture allows operations at one end wich can be called top of the stack.We can add elements or remove elements only form this en dof the stack. In a stack the element insreted last in sequence will come out first as we can remove only from the top of the stack. Such feature is known as Last in First Out(LIFO) feature. The operations of adding and removing the elements is known as PUSH and POP. In the following program we implement it as add and and remove functions. We declare an empty list and use the append() and pop() methods to add and remove the data elements. PUSH into a Stack Let us understand, how to use PUSH in Stack. Refer the program mentioned program below − Example class Stack: def __init__(self): self.stack = [] def add(self, dataval): # Use list append method to add element if dataval not in self.stack: self.stack.append(dataval) return True else: return False # Use peek to look at the top of the stack def peek(self): return self.stack[-1] AStack = Stack() AStack.add(“Mon”) AStack.add(“Tue”) AStack.peek() print(AStack.peek()) AStack.add(“Wed”) AStack.add(“Thu”) print(AStack.peek()) Output When the above code is executed, it produces the following result − Tue Thu POP from a Stack As we know we can remove only the top most data element from the stack, we implement a 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 then use the in-built pop() method to find out the top most element. class Stack: def __init__(self): self.stack = [] def add(self, dataval): # Use list append method to add element if dataval not in self.stack: self.stack.append(dataval) return True else: return False # Use list pop method to remove element def remove(self): if len(self.stack) <= 0: return (“No element in the Stack”) else: return self.stack.pop() AStack = Stack() AStack.add(“Mon”) AStack.add(“Tue”) AStack.add(“Wed”) AStack.add(“Thu”) print(AStack.remove()) print(AStack.remove()) Output When the above code is executed, it produces the following result − Thu Wed Print Page Previous Next Advertisements ”;

Python – Graphs

Python – Graphs ”; Previous Next A graph is a pictorial representation of a set of objects where some pairs of objects are connected by links. The interconnected objects are represented by points termed as vertices, and the links that connect the vertices are called edges. The various terms and functionalities associated with a graph is described in great detail in our tutorial here. In this chapter we are going to see how to create a graph and add various data elements to it using a python program. Following are the basic operations we perform on graphs. Display graph vertices Display graph edges Add a vertex Add an edge Creating a graph A 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 a look at the following graph − In the above graph, V = {a, b, c, d, e} E = {ab, ac, bd, cd, de} Example We can present this graph in a python program as below − # Create the dictionary with graph elements graph = { “a” : [“b”,”c”], “b” : [“a”, “d”], “c” : [“a”, “d”], “d” : [“e”], “e” : [“d”] } # Print the graph print(graph) Output When the above code is executed, it produces the following result − {”c”: [”a”, ”d”], ”a”: [”b”, ”c”], ”e”: [”d”], ”d”: [”e”], ”b”: [”a”, ”d”]} Display graph vertices To display the graph vertices we simple find the keys of the graph dictionary. We use the keys() method. class graph: def __init__(self,gdict=None): if gdict is None: gdict = [] 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 = { “a” : [“b”,”c”], “b” : [“a”, “d”], “c” : [“a”, “d”], “d” : [“e”], “e” : [“d”] } g = graph(graph_elements) print(g.getVertices()) Output When the above code is executed, it produces the following result − [”d”, ”b”, ”e”, ”c”, ”a”] Display graph edges Finding the graph edges is little tricker than the vertices as we have to find each of the pairs of vertices which have an edge in between them. So we create an empty list of edges then iterate through the edge values associated with each of the vertices. A list is formed containing the distinct group of edges found from the vertices. class graph: def __init__(self,gdict=None): if gdict is None: gdict = {} self.gdict = gdict def edges(self): return self.findedges() # Find the distinct list of edges def findedges(self): edgename = [] for vrtx in self.gdict: for nxtvrtx in self.gdict[vrtx]: if {nxtvrtx, vrtx} not in edgename: edgename.append({vrtx, nxtvrtx}) return edgename # Create the dictionary with graph elements graph_elements = { “a” : [“b”,”c”], “b” : [“a”, “d”], “c” : [“a”, “d”], “d” : [“e”], “e” : [“d”] } g = graph(graph_elements) print(g.edges()) Output When the above code is executed, it produces the following result − [{”b”, ”a”}, {”b”, ”d”}, {”e”, ”d”}, {”a”, ”c”}, {”c”, ”d”}] Adding a vertex Adding a vertex is straight forward where we add another additional key to the graph dictionary. Example class graph: def __init__(self,gdict=None): if gdict is None: gdict = {} self.gdict = gdict def getVertices(self): return list(self.gdict.keys()) # Add the vertex as a key def addVertex(self, vrtx): if vrtx not in self.gdict: self.gdict[vrtx] = [] # Create the dictionary with graph elements graph_elements = { “a” : [“b”,”c”], “b” : [“a”, “d”], “c” : [“a”, “d”], “d” : [“e”], “e” : [“d”] } g = graph(graph_elements) g.addVertex(“f”) print(g.getVertices()) Output When the above code is executed, it produces the following result − [”a”, ”b”, ”c”, ”d”, ”e”,”f”] Adding an edge Adding an edge to an existing graph involves treating the new vertex as a tuple and validating if the edge is already present. If not then the edge is added. class graph: def __init__(self,gdict=None): if gdict is None: gdict = {} self.gdict = gdict def edges(self): return self.findedges() # Add the new edge def AddEdge(self, edge): edge = set(edge) (vrtx1, vrtx2) = tuple(edge) if vrtx1 in self.gdict: self.gdict[vrtx1].append(vrtx2) else: self.gdict[vrtx1] = [vrtx2] # List the edge names def findedges(self): edgename = [] for vrtx in self.gdict: for nxtvrtx in self.gdict[vrtx]: if {nxtvrtx, vrtx} not in edgename: edgename.append({vrtx, nxtvrtx}) return edgename # Create the dictionary with graph elements graph_elements = { “a” : [“b”,”c”], “b” : [“a”, “d”], “c” : [“a”, “d”], “d” : [“e”], “e” : [“d”] } g = graph(graph_elements) g.AddEdge({”a”,”e”}) g.AddEdge({”a”,”c”}) print(g.edges()) Output When the above code is executed, it produces the following result − [{”e”, ”d”}, {”b”, ”a”}, {”b”, ”d”}, {”a”, ”c”}, {”a”, ”e”}, {”c”, ”d”}] Print Page Previous Next Advertisements ”;

Python – Linked Lists

Python – Linked Lists ”; Previous Next A linked list is a sequence of data elements, which are connected together via links. Each data element contains a connection to another data element in form of a 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 chapter. We have already seen how we create a node class and how to traverse the elements of a node.In this chapter we are going to study the types of linked lists known as singly linked lists. In this type of data structure there is only one link between any two data elements. We create such a list and create additional methods to insert, update and remove elements from the list. Creation of Linked list A linked list is created by using the node class we studied in the last chapter. We create a Node object and create another class to use this ode object. We pass the appropriate values through the node object to point the to the next data elements. The below program creates the linked list with three data elements. In the next section we will see how to traverse the linked list. class Node: def __init__(self, dataval=None): self.dataval = dataval self.nextval = None class SLinkedList: def __init__(self): self.headval = None list1 = SLinkedList() list1.headval = Node(“Mon”) e2 = Node(“Tue”) e3 = Node(“Wed”) # Link first Node to second node list1.headval.nextval = e2 # Link second Node to third node e2.nextval = e3 Traversing a 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. Example class Node: def __init__(self, dataval=None): self.dataval = dataval self.nextval = None class SLinkedList: def __init__(self): self.headval = None def listprint(self): printval = self.headval while printval is not None: print (printval.dataval) printval = printval.nextval list = SLinkedList() list.headval = Node(“Mon”) e2 = Node(“Tue”) e3 = Node(“Wed”) # Link first Node to second node list.headval.nextval = e2 # Link second Node to third node e2.nextval = e3 list.listprint() Output When the above code is executed, it produces the following result − Mon Tue Wed Insertion in a Linked List Inserting element in the linked list involves reassigning 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 list, we 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. So the current head of the linked list becomes the second data element and the new node becomes the head of the linked list. Example class Node: def __init__(self, dataval=None): self.dataval = dataval self.nextval = None class SLinkedList: def __init__(self): self.headval = None # Print the linked list def listprint(self): printval = self.headval while printval is not None: print (printval.dataval) printval = printval.nextval def AtBegining(self,newdata): NewNode = Node(newdata) # Update the new nodes next val to existing node NewNode.nextval = self.headval self.headval = NewNode list = SLinkedList() list.headval = Node(“Mon”) e2 = Node(“Tue”) e3 = Node(“Wed”) list.headval.nextval = e2 e2.nextval = e3 list.AtBegining(“Sun”) list.listprint() Output When the above code is executed, it produces the following result − Sun 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. Example class Node: def __init__(self, dataval=None): self.dataval = dataval self.nextval = None class SLinkedList: def __init__(self): self.headval = None # Function to add newnode def AtEnd(self, newdata): NewNode = Node(newdata) if self.headval is None: self.headval = NewNode return laste = self.headval while(laste.nextval): laste = laste.nextval laste.nextval=NewNode # Print the linked list def listprint(self): printval = self.headval while printval is not None: print (printval.dataval) printval = printval.nextval list = SLinkedList() list.headval = Node(“Mon”) e2 = Node(“Tue”) e3 = Node(“Wed”) list.headval.nextval = e2 e2.nextval = e3 list.AtEnd(“Thu”) list.listprint() Output When the above code is executed, it produces the following result − Mon Tue Wed Thu Inserting in between two Data Nodes This involves changing the pointer of a specific node to point to the new node. That is possible by passing in both the new node and the existing node after which the new node will be inserted. So we define an additional class which will change the next pointer of the new node to the next pointer of middle node. Then assign the new node to next pointer of the middle node. class Node: def __init__(self, dataval=None): self.dataval = dataval self.nextval = None class SLinkedList: def __init__(self): self.headval = None # Function to add node def Inbetween(self,middle_node,newdata): if middle_node is None: print(“The mentioned node is absent”) return NewNode = Node(newdata) NewNode.nextval = middle_node.nextval middle_node.nextval = NewNode # Print the linked list def listprint(self): printval = self.headval while printval is not None: print (printval.dataval) printval = printval.nextval list = SLinkedList() list.headval = Node(“Mon”) e2 = Node(“Tue”) e3 = Node(“Thu”) list.headval.nextval = e2 e2.nextval = e3 list.Inbetween(list.headval.nextval,”Fri”) list.listprint() Output When the above code is executed, it produces the following result − Mon Tue Fri Thu Removing an Item We can remove

Python – Graph Algorithms

Python – Graph Algorithms ”; Previous Next Graphs are very useful data structures in solving many important mathematical challenges. For example computer 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 a 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 a graph in a depth ward motion and uses a stack to remember to get the next vertex to start a search, when a dead end occurs in any iteration. We implement DFS for a graph in python using the set data types as they provide the required functionalities to keep track of visited and unvisited nodes. Example class graph: def __init__(self,gdict=None): if gdict is None: gdict = {} self.gdict = gdict # Check for the visisted and unvisited nodes def dfs(graph, start, visited = None): if visited is None: visited = set() visited.add(start) print(start) for next in graph[start] – visited: dfs(graph, next, visited) return visited gdict = { “a” : set([“b”,”c”]), “b” : set([“a”, “d”]), “c” : set([“a”, “d”]), “d” : set([“e”]), “e” : set([“a”]) } dfs(gdict, ”a”) Output When the above code is executed, it produces the following result − a b d e c Breadth First Traversal Also called breadth first search (BFS),this algorithm traverses a graph breadth ward motion and uses a queue to remember to get the next vertex to start a search, when a dead end occurs in any iteration. Please visit this link in our website to understand the details of BFS steps for a graph. We implement BFS for a 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 dequeue only the node which is left with no unvisited nodes. We stop the program when there is no next adjacent node to be visited. Example import collections class graph: def __init__(self,gdict=None): if gdict is None: gdict = {} self.gdict = gdict def bfs(graph, startnode): # Track the visited and unvisited nodes using queue seen, queue = set([startnode]), collections.deque([startnode]) while queue: vertex = queue.popleft() marked(vertex) for node in graph[vertex]: if node not in seen: seen.add(node) queue.append(node) def marked(n): print(n) # The graph dictionary gdict = { “a” : set([“b”,”c”]), “b” : set([“a”, “d”]), “c” : set([“a”, “d”]), “d” : set([“e”]), “e” : set([“a”]) } bfs(gdict, “a”) Output When the above code is executed, it produces the following result − a c b d e Print Page Previous Next Advertisements ”;

Python – Advanced Linked list

Python – Advanced Linked list ”; Previous Next We have already seen Linked List in earlier chapter in which it is possible only to travel forward. In this chapter we see another type of linked list in which it is possible to travel both forward and backward. Such a linked list is called Doubly Linked List. Following is the features of doubly linked list. Doubly Linked List contains a link element called first and last. Each link carries a data field(s) and 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 a link as null to mark the end of the list. Creating Doubly linked list We create a Doubly Linked list by using the Node class. Now we use the same approach as used in the Singly Linked List but the 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. Example class Node: def __init__(self, data): self.data = data self.next = None self.prev = None class doubly_linked_list: def __init__(self): self.head = None # Adding data elements def push(self, NewVal): NewNode = Node(NewVal) NewNode.next = self.head if self.head is not None: self.head.prev = NewNode self.head = NewNode # Print the Doubly Linked list def listprint(self, node): while (node is not None): print(node.data), last = node node = node.next dllist = doubly_linked_list() dllist.push(12) dllist.push(8) dllist.push(62) dllist.listprint(dllist.head) Output When the above code is executed, it produces the following result − 62 8 12 Inserting into Doubly Linked List Here, we are going to see how to insert a node to the Doubly Link List using the following program. The program uses a method named insert which inserts the new node at the third position from the head of the doubly linked list. Example # Create the Node class class Node: def __init__(self, data): self.data = data self.next = None self.prev = None # Create the doubly linked list class doubly_linked_list: def __init__(self): self.head = None # Define the push method to add elements def push(self, NewVal): NewNode = Node(NewVal) NewNode.next = self.head if self.head is not None: self.head.prev = NewNode self.head = NewNode # Define the insert method to insert the element def insert(self, prev_node, NewVal): if prev_node is None: return NewNode = Node(NewVal) NewNode.next = prev_node.next prev_node.next = NewNode NewNode.prev = prev_node if NewNode.next is not None: NewNode.next.prev = NewNode # Define the method to print the linked list def listprint(self, node): while (node is not None): print(node.data), last = node node = node.next dllist = doubly_linked_list() dllist.push(12) dllist.push(8) dllist.push(62) dllist.insert(dllist.head.next, 13) dllist.listprint(dllist.head) Output When the above code is executed, it produces the following result − 62 8 13 12 Appending to a Doubly linked list Appending to a doubly linked list will add the element at the end. Example # Create the node class class Node: def __init__(self, data): self.data = data self.next = None self.prev = None # Create the doubly linked list class class doubly_linked_list: def __init__(self): self.head = None # Define the push method to add elements at the begining def push(self, NewVal): NewNode = Node(NewVal) NewNode.next = self.head if self.head is not None: self.head.prev = NewNode self.head = NewNode # Define the append method to add elements at the end def append(self, NewVal): NewNode = Node(NewVal) NewNode.next = None if self.head is None: NewNode.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 def listprint(self, node): while (node is not None): print(node.data), last = node node = node.next dllist = doubly_linked_list() dllist.push(12) dllist.append(9) dllist.push(8) dllist.push(62) dllist.append(45) dllist.listprint(dllist.head) Output When the above code is executed, it produces the following result − 62 8 12 9 45 Please note the position of the elements 9 and 45 for the append operation. Print Page Previous Next Advertisements ”;

Python – DS Home

Python – Data structures Tutorial PDF Version Quick Guide Resources Job Search Discussion Computers store and process data with an extra ordinary speed and accuracy. So, it is highly essential that the data is stored efficiently and can be accessed fast. Also, the processing of data should happen in the smallest possible time, but without losing the accuracy. Data structures deal with how the data is organised and held in the memory, when a program processes it. It is important to note that, the data that is stored in the disk as part of persistent storages (like relational tables) are not referred as data structure here. An Algorithm is step by step set of instruction to process the data for a specific purpose. So, an algorithm utilises various data structures in a logical way to solve a specific computing problem. In this tutorial, we will cover these two fundamental concepts of computer science using the Python programming language. Audience This tutorial is designed for Computer Science graduates as well as Software Professionals who are willing to learn data structures and algorithm programming in simple and easy steps using Python as a programming language. Prerequisites Before proceeding with this tutorial, you should have a basic knowledge of writing code in Python programming language, using any python integrated development environment (IDE) and execution of Python programs. If you are completely new to python, then please refer our Python tutorial to get a sound understanding of the language. Print Page Previous Next Advertisements ”;

Python – Matrix

Python – Matrix ”; Previous Next Matrix is a special case of two dimensional array where each data element is of strictly same size. So every matrix is also a two dimensional array but not vice versa. Matrices are very important data structures for many mathematical and scientific calculations. As we have already discussed two dimnsional array data structure in the previous chapter we will be focusing on data structure operations specific to matrices in this chapter. We also be using the numpy package for matrix data manipulation. Matrix Example Consider the case of recording temprature for 1 week measured in the morning, mid-day, evening and mid-night. It can be presented as a 7X5 matrix using an array and the reshape method available in numpy. from numpy import * a = array([[”Mon”,18,20,22,17],[”Tue”,11,18,21,18], [”Wed”,15,21,20,19],[”Thu”,11,20,22,21], [”Fri”,18,17,23,22],[”Sat”,12,22,20,18], [”Sun”,13,15,19,16]]) m = reshape(a,(7,5)) print(m) Output The above data can be represented as a two dimensional array as below − [ [”Mon” ”18” ”20” ”22” ”17”] [”Tue” ”11” ”18” ”21” ”18”] [”Wed” ”15” ”21” ”20” ”19”] [”Thu” ”11” ”20” ”22” ”21”] [”Fri” ”18” ”17” ”23” ”22”] [”Sat” ”12” ”22” ”20” ”18”] [”Sun” ”13” ”15” ”19” ”16”] ] Accessing Values The data elements in a matrix can be accessed by using the indexes. The access method is same as the way data is accessed in Two dimensional array. Example from numpy import * m = array([[”Mon”,18,20,22,17],[”Tue”,11,18,21,18], [”Wed”,15,21,20,19],[”Thu”,11,20,22,21], [”Fri”,18,17,23,22],[”Sat”,12,22,20,18], [”Sun”,13,15,19,16]]) # Print data for Wednesday print(m[2]) # Print data for friday evening print(m[4][3]) Output When the above code is executed, it produces the following result − [”Wed”, 15, 21, 20, 19] 23 Adding a row Use the below mentioned code to add a row in a matrix. Example from numpy import * m = array([[”Mon”,18,20,22,17],[”Tue”,11,18,21,18], [”Wed”,15,21,20,19],[”Thu”,11,20,22,21], [”Fri”,18,17,23,22],[”Sat”,12,22,20,18], [”Sun”,13,15,19,16]]) m_r = append(m,[[”Avg”,12,15,13,11]],0) print(m_r) Output When the above code is executed, it produces the following result − [ [”Mon” ”18” ”20” ”22” ”17”] [”Tue” ”11” ”18” ”21” ”18”] [”Wed” ”15” ”21” ”20” ”19”] [”Thu” ”11” ”20” ”22” ”21”] [”Fri” ”18” ”17” ”23” ”22”] [”Sat” ”12” ”22” ”20” ”18”] [”Sun” ”13” ”15” ”19” ”16”] [”Avg” ”12” ”15” ”13” ”11”] ] Adding a column We can add column to a matrix using the insert() method. here we have to mention the index where we want to add the column and a array containing the new values of the columns added.In the below example we add t a new column at the fifth position from the beginning. Example from numpy import * m = array([[”Mon”,18,20,22,17],[”Tue”,11,18,21,18], [”Wed”,15,21,20,19],[”Thu”,11,20,22,21], [”Fri”,18,17,23,22],[”Sat”,12,22,20,18], [”Sun”,13,15,19,16]]) m_c = insert(m,[5],[[1],[2],[3],[4],[5],[6],[7]],1) print(m_c) Output When the above code is executed, it produces the following result − [ [”Mon” ”18” ”20” ”22” ”17” ”1”] [”Tue” ”11” ”18” ”21” ”18” ”2”] [”Wed” ”15” ”21” ”20” ”19” ”3”] [”Thu” ”11” ”20” ”22” ”21” ”4”] [”Fri” ”18” ”17” ”23” ”22” ”5”] [”Sat” ”12” ”22” ”20” ”18” ”6”] [”Sun” ”13” ”15” ”19” ”16” ”7”] ] Delete a row We can delete a row from a matrix using the delete() method. We have to specify the index of the row and also the axis value which is 0 for a row and 1 for a column. Example from numpy import * m = array([[”Mon”,18,20,22,17],[”Tue”,11,18,21,18], [”Wed”,15,21,20,19],[”Thu”,11,20,22,21], [”Fri”,18,17,23,22],[”Sat”,12,22,20,18], [”Sun”,13,15,19,16]]) m = delete(m,[2],0) print(m) Output When the above code is executed, it produces the following result − [ [”Mon” ”18” ”20” ”22” ”17”] [”Tue” ”11” ”18” ”21” ”18”] [”Thu” ”11” ”20” ”22” ”21”] [”Fri” ”18” ”17” ”23” ”22”] [”Sat” ”12” ”22” ”20” ”18”] [”Sun” ”13” ”15” ”19” ”16”] ] Delete a column We can delete a column from a matrix using the delete() method. We have to specify the index of the column and also the axis value which is 0 for a row and 1 for a column. Example from numpy import * m = array([[”Mon”,18,20,22,17],[”Tue”,11,18,21,18], [”Wed”,15,21,20,19],[”Thu”,11,20,22,21], [”Fri”,18,17,23,22],[”Sat”,12,22,20,18], [”Sun”,13,15,19,16]]) m = delete(m,s_[2],1) print(m) Output When the above code is executed, it produces the following result − [ [”Mon” ”18” ”22” ”17”] [”Tue” ”11” ”21” ”18”] [”Wed” ”15” ”20” ”19”] [”Thu” ”11” ”22” ”21”] [”Fri” ”18” ”23” ”22”] [”Sat” ”12” ”20” ”18”] [”Sun” ”13” ”19” ”16”] ] Update a row To update the values in the row of a matrix we simply re-assign the values at the index of the row. In the below example all the values for thrusday”s data is marked as zero. The index for this row is 3. Example from numpy import * m = array([[”Mon”,18,20,22,17],[”Tue”,11,18,21,18], [”Wed”,15,21,20,19],[”Thu”,11,20,22,21], [”Fri”,18,17,23,22],[”Sat”,12,22,20,18], [”Sun”,13,15,19,16]]) m[3] = [”Thu”,0,0,0,0] print(m) Output When the above code is executed, it produces the following result − [ [”Mon” ”18” ”20” ”22” ”17”] [”Tue” ”11” ”18” ”21” ”18”] [”Wed” ”15” ”21” ”20” ”19”] [”Thu” ”0” ”0” ”0” ”0”] [”Fri” ”18” ”17” ”23” ”22”] [”Sat” ”12” ”22” ”20” ”18”] [”Sun” ”13” ”15” ”19” ”16”] ] Print Page Previous Next Advertisements ”;

Python – Dictionary

Python – Dictionary ”; Previous Next In Dictionary each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this − {}. Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. Accessing Values in Dictionary To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Example A simple example is as follows − #!/usr/bin/python dict = {”Name”: ”Zara”, ”Age”: 7, ”Class”: ”First”} print (“dict[”Name”]: “, dict[”Name”]) print (“dict[”Age”]: “, dict[”Age”]) Output When the above code is executed, it produces the following result − dict[”Name”]: Zara dict[”Age”]: 7 If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows − Example #!/usr/bin/python dict = {”Name”: ”Zara”, ”Age”: 7, ”Class”: ”First”} print (“dict[”Alice”]: “, dict[”Alice”]) Output When the above code is executed, it produces the following result − dict[”Alice”]: Traceback (most recent call last): File “test.py”, line 4, in <module> print “dict[”Alice”]: “, dict[”Alice”]; KeyError: ”Alice” Updating Dictionary You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example − Example #!/usr/bin/python dict = {”Name”: ”Zara”, ”Age”: 7, ”Class”: ”First”} dict[”Age”] = 8; # update existing entry dict[”School”] = “DPS School”; # Add new entry print (“dict[”Age”]: “, dict[”Age”]) print (“dict[”School”]: “, dict[”School”]) Output When the above code is executed, it produces the following result − dict[”Age”]: 8 dict[”School”]: DPS School Delete Dictionary Elements You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation. Example To explicitly remove an entire dictionary, just use the del statement. A simple example is as mentioned below − #!/usr/bin/python dict = {”Name”: ”Zara”, ”Age”: 7, ”Class”: ”First”} del dict[”Name”]; # remove entry with key ”Name” dict.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 raised because after del dict dictionary does not exist any more − Output This produces the following result − dict[”Age”]: dict[”Age”] dict[”School”]: dict[”School”] Note − del() method is discussed in subsequent section. Properties of Dictionary Keys Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same 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 means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. For example #!/usr/bin/python dict = {”Name”: ”Zara”, ”Age”: 7, ”Name”: ”Manni”} print (“dict[”Name”]: “, dict[”Name”]) Output When the above code is executed, it produces the following result − dict[”Name”]: Manni Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like [”key”] is not allowed. Example An example is as follows − #!/usr/bin/python dict = {[”Name”]: ”Zara”, ”Age”: 7} print (“dict[”Name”]: “, dict[”Name”]) Output When the above code is executed, it produces the following result − Traceback (most recent call last): File “test.py”, line 3, in <module> dict = {[”Name”]: ”Zara”, ”Age”: 7}; TypeError: list objects are unhashable Print Page Previous Next Advertisements ”;

Python – DS Introduction

Python – DS Introduction ”; Previous Next Here, we will understand what is data structure with regards to Python programming language. Data Structure Overview Data structures are fundamental concepts of computer science which helps is writing efficient programs in any language. Python is a high-level, interpreted, interactive and object-oriented scripting language using which we can study the fundamentals of data structure in a simpler way as compared to other programming languages. In this chapter we are going to study a 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 is listed as another category. General Data Structures The various data structures in computer science are divided broadly into two categories shown below. We will discuss about each of the below data structures in detail in subsequent chapters. Liner Data Structures These are the data structures which store the data elements in a sequential manner. Array − It is a sequential arrangement of data elements paired with the index of the data element. Linked List − Each data element contains a link to another element along with the data present in it. Stack − It is a data structure which follows only to specific order of operation. LIFO(last in First Out) or FILO(First in Last Out). Queue − It is similar to Stack but the order of operation is only FIFO(First In First Out). Matrix − It is two dimensional data structure in which the data element is referred by a pair of indices. Non-Liner Data Structures These are the data structures in which there 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 a strict sequence. Binary Tree − It is a data structure where each data element can be connected to maximum two other data elements and it starts with a root node. Heap − It is a special case of Tree data structure where the data in the parent node is either strictly greater than/ equal to the child nodes or strictly less than it’s child nodes. Hash Table − It is a data structure which is made of arrays associated with each other using a hash function. It retrieves values using keys rather than index from a data element. Graph − It is an arrangement of vertices and nodes where 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. List − It is similar to array with the exception that the data elements can be of different data types. You can have both numeric and string data in a python list. Tuple − Tuples are similar to lists but they are immutable which means the values in a tuple cannot be modified they can only be read. Dictionary − The dictionary contains Key-value pairs as its data elements. In the next chapters we are going to learn the details of how each of these data structures can be implemented using Python. Print Page Previous Next Advertisements ”;