Python Tutorial

Introduction Python Features Python Applications System requirements for Python Python Installation Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Anonymous/Lambda Function in Python

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor

Python Iterators

Iterators in Python Yield Statement In Python

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Calendar Module  

Python MySQL

Python MySQL Python MySQL Update Operation Python MySQL Delete Operation

Python MongoDB

Python MongoDB

Python Data Structure Implementation

Python Stack Python Queue Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Collections in python Python Enumerate Python Debugger Python DefaultDict

Misc

Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering List Comprehension in Python3 NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Logical Operators Python Multiprocessing Python History Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Design patterns in python Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python Abstract design pattern in python Builder design pattern in python

How to

How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python Singleton design pattern in python

Python Graph

Python Graph: In Computer Science and Mathematics, a Graph is a pictorial representation of a group of objects or elements where some elements are connected using the links. A graph is the network of vertices (also known as nodes) that may or may not be interconnected. These vertices are connected using a path or a line known as an edge. We will be discussing a lot related to the terms used in the Graph and its various functionalities in this section. We will be discovering various things, such as creating a graph and adding several data elements to the Graph using Python programming.

Let’s start with a basic difference between directed and undirected graphs. If the edges in Graph have a specific flow direction, where the direction edge is known as an arc called Graph is directed. At the same time, the Graph with no specified directions is said to be undirected.

Graph plays a significant role in Data Science and it is often practiced in solving real-world problems. Various sectors depend on the Graph and its theories and principles, including molecular studies in chemistry and biology, maps, networks, recommender systems, and a lot.

These are some basic operations we are going to perform on graphs in the following sections.

  1. Displaying Vertices of the graph.
  2. Displaying Edges of the graph.
  3. Adding a Vertex.
  4. Adding an Edge.
  5. Creating a Graph.

We can implement a Graph with the help of Python Dictionary data structures. We will represent the graph vertices as the dictionary keys and the edges as the values associated with each key in the dictionary.

Let’s have a look at the graph shown below:

Python Graph

As we can observe in the above graph

Vertices = {p, q, r, s, t}
Edges = {pq, pr, qs, rs, st}

In Python, the above graph can be represented in the syntax, as shown below:

# Creating a dictionary using the graph elements
 my_graph = {"p" : ["q","r"],
           "q" : ["p", "s"],
           "r" : ["p", "s"],
           "s" : ["t"],
           "t" : ["s"]
          }
 # Printing the final graph       
 print("This is my graph: \n", my_graph) 

The above snippet of code should produce an Output, as shown below:

This is my graph:
 {'p': ['q', 'r'], 'q': ['p', 's'], 'r': ['p', 's'], 's': ['t'], 't': ['s']}

Displaying Vertices of the Graph

We can display the vertices of the graph by finding the keys of the graph dictionary using the keys() method. Let’s have a look at the following example:

class my_graph:
     def __init__(self, g_dict = None):
         if g_dict is None:
             g_dict = []
         self.g_dict = g_dict
 # Geting the keys of the dictionary
     def myVertices(self):
         return list(self.g_dict.keys())
 # Creating a dictionary using the graph elements
 my_graph_elements = {
     "p" : ["q","r"],
     "q" : ["p", "s"],
     "r" : ["p", "s"],
     "s" : ["t"],
     "t" : ["s"]
     }
 x = my_graph(my_graph_elements)
 print("The Vertices of my graph: \n", x.myVertices()) 

The above snippet of code should produce an Output, as shown below:

The Vertices of my graph:
 ['p', 'q', 'r', 's', 't']

Displaying Edges of the Graph

It is slightly hard to find the edges of a graph than to find the vertices because we need to find each of the vertices pairs that hold an edge in between them. Thus, we can build an empty list holding the edges and then we can iterate through the edge values linked with each of the vertices. Then, we will get the complete list holding the different group of edges originated from the vertices. Let's have a look at an example given below:

class my_graph:
     def __init__(self, g_dict = None):
         if g_dict is None:
             g_dict = {}
         self.g_dict = g_dict
     def my_edges(self):
         return self.find_my_edges()
 # Finding the distinct list of edges
     def find_my_edges(self):
         edge_name = []
         for vertx in self.g_dict:
             for next_vrtx in self.g_dict[vertx]:
                 if {next_vrtx, vertx} not in edge_name:
                     edge_name.append({vertx, next_vrtx})
         return edge_name
 # Creating a dictionary using the graph elements
 my_graph_elements = {
     "p" : ["q","r"],
     "q" : ["p", "s"],
     "r" : ["p", "s"],
     "s" : ["t"],
     "t" : ["s"]
     }
 x = my_graph(my_graph_elements)
 print("The Edges of my graph: \n", x.my_edges()) 

The above snippet of code should produce an Output, as shown below:

The Edges of my graph:
 [{'q', 'p'}, {'p', 'r'}, {'s', 'q'}, {'s', 'r'}, {'s', 't'}]

Inserting a Vertex

We can add a vertex by adding a key to the graph dictionary. Let’s have a look at an example shown below:

class my_graph:
     def __init__(self, g_dict = None):
         if g_dict is None:
             g_dict = {}
         self.g_dict = g_dict
     def get_Vertices(self):
         return list(self.g_dict.keys())
 # Adding the vertex as a key
     def add_Vertex(self, vertx):
        if vertx not in self.g_dict:
             self.g_dict[vertx] = []
 # Creating a dictionary using the graph elements
 my_graph_elements = {
     "p" : ["q","r"],
     "q" : ["p", "s"],
     "r" : ["p", "s"],
     "s" : ["t"],
     "t" : ["s"]
     }
 x = my_graph(my_graph_elements)
 x.add_Vertex("u")
 print("The Vertices of the graph: \n", x.get_Vertices()) 

The above snippet of code should produce an Output, as shown below:

The Vertices of the graph:
 ['p', 'q', 'r', 's', 't', 'u']

Inserting an Edge

The process of adding an edge to a current graph involves the following procedure:

  • First of all, we need to treat the new vertex as a tuple.
  • Then, we need to validate if any edge is already present.

If no edge is present there, we can add one as shown in the following example:

class my_graph:
     def __init__(self, g_dict = None):
         if g_dict is None:
             g_dict = {}
         self.g_dict = g_dict
     def my_edges(self):
         return self.find_edges()
 # Adding the new edge
     def Add_Edge(self, my_edge):
         my_edge = set(my_edge)
         (vrtx_a, vrtx_b) = tuple(my_edge)
         if vrtx_a in self.g_dict:
             self.g_dict[vrtx_a].append(vrtx_b)
         else:
             self.g_dict[vrtx_a] = [vrtx_b]
 # Listing the edge names
     def find_edges(self):
         edge_name = []
         for vertx in self.g_dict:
             for next_vrtx in self.g_dict[vertx]:
                 if {next_vrtx, vertx} not in edge_name:
                     edge_name.append({vertx, next_vrtx})
         return edge_name
 # Creating a dictionary using the graph elements
 my_graph_elements = {
     "p" : ["q","r"],
     "q" : ["p", "s"],
     "r" : ["p", "s"],
     "s" : ["t"],
     "t" : ["s"]
     }
 x = my_graph(my_graph_elements)
 x.Add_Edge({'p','t'})
 x.Add_Edge({'p','r'})
 print("The Edges of my graph: \n", x.my_edges()) 

The above snippet of code should produce an Output, as shown below:

The Edges of my graph:
 [{'q', 'p'}, {'p', 'r'}, {'q', 's'}, {'s', 'r'}, {'t', 's'}, {'t', 'p'}]



ADVERTISEMENT
ADVERTISEMENT