Please write a Python function that generates an undirected, weighted, fully connected graph with a given number of nodes. Each node should contain two integers between 0 and 1000, representing X and Y coordinates. The edge weights should be the euclidian distance between the nodes sharing that edge.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a Python function that generates an undirected, weighted, fully connected graph as per your specifications. This function utilizes the NetworkX library for graph creation and manipulation, and the numpy library for efficient numerical computations (specifically for generating random coordinates and calculating Euclidean distances). If you haven't installed these libraries yet, you can do so by running pip install networkx numpy.
python
import networkx as nx
import numpy as np
def generate_fully_connected_weighted_graph(num_nodes: int, coord_range: int = 1000) -> nx.Graph:
"""
Generates an undirected, weighted, fully connected graph with a given number of nodes.
Each node contains two integers between 0 and coord_range, representing X and Y coordinates.
The edge weights are the Euclidean distances between the nodes sharing that edge.
Parameters:
- num_nodes (int): The number of nodes in the graph.
- coord_range (int, optional): The upper limit for the random X and Y coordinates. Defaults to 1000.
Returns:
- nx.Graph: A fully connected, undirected, weighted graph.
"""
# Create an empty undirected graph
G = nx.Graph()
# Generate random coordinates for each node and add them to the graph
for node in range(num_nodes):
# Generate random X and Y coordinates within the specified range
x, y = np.random.randint(0, coord_range + 1, size=2)
# Add the node with its coordinates
G.add_node(node, coords=(x, y))
# Iterate over all pairs of nodes to connect them with weighted edges
for node1 in G.nodes:
for node2 in G.nodes:
if node1 < node2: # Only consider each pair once for efficiency
# Extract the coordinates of the current pair of nodes
(x1, y1) = G.nodes[node1]['coords']
(x2, y2) = G.nodes[node2]['coords']
# Calculate the Euclidean distance between the two nodes
weight = np.sqrt((x2 - x1)**2 + (y2 - y1)**2)
# Add an edge between the two nodes with the calculated weight
G.add_edge(node1, node2, weight=weight)
return G
# Example usage:
if __name__ == "__main__":
num_nodes_example = 5
graph = generate_fully_connected_weighted_graph(num_nodes_example)
# Display node coordinates
print("Node Coordinates:")
for node, attrs in graph.nodes(data=True):
print(f"Node {node}: {attrs['coords']}")
# Display edge weights
print("\nEdge Weights:")
for edge, attrs in graph.edges(data=True):
print(f"Edge {edge}: Weight = {attrs['weight']:.2f}")
This script does the following:
Defines a function generate_fully_connected_weighted_graph that takes the number of nodes and an optional coordinate range as inputs.
Generates random integer X and Y coordinates for each node within the specified range.
Connects every node to every other node efficiently by only considering each pair once (using if node1 < node2), calculating the Euclidean distance as the weight for each edge.
Provides an example usage at the end, demonstrating how to create a graph with 5 nodes and display their coordinates and the weights of the edges between them.
Note: For large inputs (i.e., a high number of nodes), this function may be slow because it has a time complexity of O(n^2) due to the nested loop structure. This is unavoidable for a fully connected graph since every node must be connected to every other node, resulting in n*(n-1)/2 edges. However, the optimization if node1 < node2 ensures that each edge is only processed once, improving efficiency compared to processing each pair twice.