Getting Started With The Python Data Structure
Listed below are important Data Structures from which you can learn how to use them in Python
By modifying code and applying logic you can solve many problems related to Data Structures and Algorithms
This is for someone who already knows Data Structures in other languages like C++ or Java and they want to switch language to learn python for Data Science and Artificial Intelligence it will be beneficial for them to get started with Data Structures and Algorithms in python
Here I have not included Fenwick tree, Segment tree and Trie Data Structures to keep it simple but you should also learn this
How to use Stack in python
It is represented by python list
stack = []
append() function to push
stack.append('A')
pop() function to pop
my_stack.pop()
How to use Queue in python
You can use queue package of python
put() function to Enqueue
from queue import Queue
queue=Queue()
queue.put("A")
get() function to Dequeue
queue.get()
How to use Deque (Doubly Ended Queue) in python
For this you can use deque from collection package of python
from collections import deque
deque = deque(["A","B","C"])
append() : This function is used to insert the value in its argument to the right end of deque
appendleft() : This function is used to insert the value in its argument to the left end of deque
pop() : This function is used to delete an argument from the right end of deque
popleft() : This function is used to delete an argument from the left end of deque
For Example:
deque.append("E")
deque.appendleft("F")
deque.pop()
deque.popleft()
How to use Priority Queue in python
For this you can use priorityQueue from queue package of python
The elements are inserted with the put() method
With the use of the get() method, the elements are dequeued using the while loop
For example:
from queue import priorityQueue
q = PriorityQueue()
q.put((30,'Black balls'))
q.put((8,'Red balls'))
q.put((7,'Yellow balls'))
q.put((4,'Pink balls'))
while not q.empty():
item = q.get()
print(item)
How to use Ordered Dictionary in python
For this you can use OrderedDict from collections package of python
It works same as dictionary but remembers the order that keys were first inserted
For Example:
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
for key, value in od.items():
print(key, value)
od.pop('c')
How to use set in python
You can use with set() constructor
For example:
myset = set(("apple", "banana", "mango"))
You cannot access items in a set by referring to an index or a key
But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword
for x in myset:
print(x)
To remove an item in a set, use the remove(), or the discard() method.
myset.remove("banana")
You can also use the pop() method to remove an item, but this method will remove the last item
Remember that sets are unordered, so you will not know what item that gets removed.
x = myset.pop()
Similarly to mathematical functions such as union, intersection, and difference, you can manipulate sets all functions are available for this in python
How to use Heaps in python
You can use heapq package of python
heapify : Lists can be converted to heaps with this function the smallest element in the heap is pushed to the index position 0 and the rest of the data elements are not necessarily sorted
heappush : Adds a new element to the heap without changing the current heap
heappop : Returns the smallest data element from the heap.
heapreplace : Replaces the smallest data element in the heap with a new value supplied by the function
Mean Heap:
For example:
import heapq
H = [10,12,93,87,23,52]
heapq.heapify(H)
heapq.heappush(H,18)
heapq.heappop(H)
heapq.heapreplace(H,16)
Max Heap:
By multiplying all elements of heap you can also use it as max heap
For example:
from heapq import heappop, heappush, heapify
heap = []
heapify(heap)
heappush(heap, -1 * 10)
heappush(heap, -1 * 40)
heappush(heap, -1 * 70)
heappush(heap, -1 * 100)
max_element=heappop(heap)*-1
Returns the maximum data element from the heap by multiplying again with -1
How to use linked list in python
python class is a node which will contain value and address of other node
python object of that class will hold address of the node
You can access node with the object of that node(Class)
For example:
class Node():
def __init__(self, value=None):
self.value = value
self.nextNode = None
node1 = Node(1)
head=node1
node2= Node(3)
node1.nextNode= node2
In this you can create linked list
How to use tree in python
python class is a tree node which will contain value and address of others child node
python object of that class will hold address of the tree node
You can access tree node with the object of that tree node
For example:
class Node:
def __init__(self, value=None):
self.value = value
self.rightNode = None
self.leftNode = None
root = Node(2)
leftchild= Node(1)
rightchild= Node(3)
root.rightNode = rightchild
root.leftNode= leftchild
In this way you can create tree
How to use Graph in python
Graph is represented by adjacency list this is easy and efficiently way to represent graph
For this you can use defaultdict from collection package of python
If a key isn't in the dictionary, the defaultdict would add it and provide whatever default value you set (in that case a list)
You can create graph with edges and vertices using helper function named add edges by calling that function again and again with edge and vertex like
For example:
from collections import defaultdict
class Graph():
def __init__(self,directed):
self.graph=defaultdict(list)
self.directed=directed
def add_edge(self,u,v):
if self.directed:
self.graph[u].append(v)
else:
self.graph[u].append(v)
self.graph[v].append(u)
g=Graph(True)
g.add_edge("A","B")
g.add_edge("A","C")
g.graph
That means vertex B and vertex C connected by an edge to the vertex A
In this way you can create graph
How to use Weighted Graph in python
For this you can use defaultdict from collection package of python
If a key isn't in the dictionary, the defaultdict would add it and provide whatever default value you set (in that case a dictionary)
For example:
from collections import defaultdict
class WeightedGraph():
def __init__(self,directed):
self.graph=defaultdict(dict)
self.directed=directed
def add_edge(self,u,v,weight):
if self.directed:
self.graph[u][v]=weight
else:
self.graph[u][v]=weight
self.graph[v][u]=weight
g=WeightedGraph(True)
g.add_edge("A","B",23)
g.add_edge("A","C",23)
g.add_edge("B","A",23)
g.graph
In this way you can create Weighted graph