How to Represent a Graph Using Sets and Hashes in Python?

Estimated read time 2 min read

In Python, you can represent a graph using sets and hashes (dictionaries) by considering each node as a key in the dictionary, and the corresponding value is a set of its adjacent nodes. Here’s an example of how you can create a graph using sets and hashes in Python:

class Graph:
    def __init__(self):
        self.graph = {}

    def add_edge(self, node1, node2):
        # Add node2 to the adjacency set of node1
        if node1 in self.graph:
            self.graph[node1].add(node2)
        else:
            self.graph[node1] = {node2}

        # Add node1 to the adjacency set of node2
        if node2 in self.graph:
            self.graph[node2].add(node1)
        else:
            self.graph[node2] = {node1}

    def remove_edge(self, node1, node2):
        # Remove node2 from the adjacency set of node1
        if node1 in self.graph:
            self.graph[node1].discard(node2)

        # Remove node1 from the adjacency set of node2
        if node2 in self.graph:
            self.graph[node2].discard(node1)

    def get_neighbors(self, node):
        # Return the set of neighbors of the given node
        if node in self.graph:
            return self.graph[node]
        else:
            return set()

    def has_edge(self, node1, node2):
        # Check if there is an edge between node1 and node2
        return node1 in self.graph and node2 in self.graph[node1]

    def __str__(self):
        # Print the graph in an easily readable format
        result = ""
        for node in self.graph:
            neighbors = ", ".join(str(n) for n in self.graph[node])
            result += f"{node}: {neighbors}\n"
        return result


# Create a graph object
graph = Graph()

# Add edges to the graph
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(2, 3)
graph.add_edge(3, 4)
graph.add_edge(4, 5)

# Print the graph
print(graph)

# Get the neighbors of a node
print(graph.get_neighbors(3))

# Check if there is an edge between two nodes
print(graph.has_edge(2, 4))

# Remove an edge from the graph
graph.remove_edge(1, 3)

# Print the updated graph
print(graph)

In the above code, the Graph class represents the graph and provides methods to add edges, remove edges, get neighbors of a node, and check for an edge between two nodes. The graph is stored in the self.graph dictionary, where each key is a node, and the corresponding value is a set of its adjacent nodes.

You can run this code and see how the graph is represented and manipulated using sets and hashes in Python.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply