Advertisement
Python253

topological_sort_demo

Jun 24th, 2024
473
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.11 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: topological_sort_demo.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.  
  10.    - Topological sorting arranges the vertices of a directed graph in a linear order.
  11.    - This ensures that for every directed edge UV from vertex U to vertex V, vertex U precedes vertex V in the ordered sequence.
  12.    - Topological Sorting is feasible only in Directed Acyclic Graphs (DAGs), where no cycles exist among the vertices.
  13.    - Kahn's Algorithm is a common method for topological sorting.
  14.    - It involves iteratively removing nodes with no incoming edges and subsequently removing their outgoing edges from the graph.
  15.  
  16. Requirements:
  17.    - Python 3.x
  18.  
  19. Functions:
  20.    - topological_sort(input_graph):
  21.        Perform topological sorting on the given directed graph `input_graph` using Kahn's Algorithm.
  22.  
  23. Usage:
  24.    - Run the script to see an example of topological sorting in action.
  25.  
  26. Additional Notes:
  27.    - This implementation assumes the input graph `input_graph` is represented as a dictionary.
  28.    - Keys are vertices and values are lists of vertices they have directed edges to.
  29.    - Returns a list representing the topological order of vertices if the graph is a Directed Acyclic Graph (DAG).
  30.    - If not a DAG it returns an error message indicating the presence of cycles in the graph.
  31.  
  32. Example:
  33.    >>> example_graph = {
  34.    ...     'A': ['B', 'C'],
  35.    ...     'B': ['D', 'E'],
  36.    ...     'C': ['F'],
  37.    ...     'D': [],
  38.    ...     'E': ['F'],
  39.    ...     'F': [],
  40.    ...     'G': ['H'],
  41.    ...     'H': ['I'],
  42.    ...     'I': []
  43.    ... }
  44.    >>> print(topological_sort(example_graph))
  45.    ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
  46. """
  47.  
  48. from collections import deque
  49.  
  50. def topological_sort(input_graph):
  51.     """
  52.    Perform topological sorting on the given directed graph `input_graph` using Kahn's Algorithm.
  53.  
  54.    Args:
  55.        input_graph (dict): A dictionary representing the directed graph. Keys are vertices,
  56.                            and values are lists of vertices they have directed edges to.
  57.  
  58.    Returns:
  59.        list or str: A list representing the topological order of vertices if the graph
  60.                     is a Directed Acyclic Graph (DAG), otherwise returns an error message
  61.                     indicating the presence of cycles in the graph.
  62.    """
  63.     # Calculate in-degree (number of incoming edges) for each node
  64.     in_degree = {u: 0 for u in input_graph}  # Initialize in-degree as 0 for all vertices
  65.     for u in input_graph:
  66.         for v in input_graph[u]:
  67.             in_degree[v] += 1
  68.  
  69.     # Queue for all nodes with no incoming edge
  70.     queue = deque([u for u in input_graph if in_degree[u] == 0])
  71.    
  72.     top_order = []  # List to store the topological order
  73.  
  74.     while queue:
  75.         # Sort vertices with the same in-degree lexicographically
  76.         queue = deque(sorted(queue))
  77.        
  78.         u = queue.popleft()  # Choose the vertex with no incoming edges
  79.         top_order.append(u)
  80.  
  81.         # Decrease in-degree by 1 for all its neighboring nodes
  82.         for v in input_graph[u]:
  83.             in_degree[v] -= 1
  84.             # If in-degree becomes zero, add it to the queue
  85.             if in_degree[v] == 0:
  86.                 queue.append(v)
  87.  
  88.     # Check if there was a cycle
  89.     if len(top_order) != len(input_graph):
  90.         return "The graph has at least one cycle and cannot be topologically sorted."
  91.     else:
  92.         return top_order
  93.  
  94. if __name__ == "__main__":
  95.     # Example usage
  96.     example_graph = {
  97.         'A': ['B', 'C'],
  98.         'B': ['D', 'E'],
  99.         'C': ['F'],
  100.         'D': [],
  101.         'E': ['F'],
  102.         'F': [],
  103.         'G': ['H'],
  104.         'H': ['I'],
  105.         'I': []
  106.     }
  107.    
  108.     # Print the example graph
  109.     print("\n\t\tExample Graph:\n\t\t--------------")
  110.     for vertex in example_graph:
  111.         print(f"\t\t{vertex}: {example_graph[vertex]}")
  112.  
  113.     # Perform topological sort and print the result
  114.     print("\n\t\tTopological Sort:\n\t\t-----------------")
  115.     sorted_order = topological_sort(example_graph)
  116.     print("\t       ", sorted_order)
  117.  
  118.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement