I just finished implementing a working Python code for the Dijkstra-Pathfinding algorithm. I am applying this algorithm to a graph with edges, which I have written as a list of tuples:
graph = Graph([
("a", "b", 2),("a", "c", 5),
("a", "d", 2),("b", "c", 3),
("b", "e", 1),("c", "e", 1),
("c", "h", 1),("c", "f", 1),
("c", "d", 3),("d", "g", 2),
("e", "i", 7),("f", "h", 3),
("f", "g", 2),("h", "i", 1)])
I don't want to leave it like that and rather fill the graph using a for-loop, but this is exactly where I fail.
I have tried writing
graph.append(("i", "j", "4"))
And several other variants using the append function but it just keeps giving me errors. I am aware that this isn't a for-loop, I am simply trying to add one edge for now.
CodePudding user response:
In this line the parenthesis are serving as a container for multiple string arguments.
graph.append("i", "j", "4")
You need to add a layer of nested parenthesis to indicate that the argument is a single tuple.
graph.append(("i", "j", "4"))
CodePudding user response:
To add an edge to a graph, you can use the add_edge method of the Graph class. This method takes three arguments: the source node, the destination node, and the weight of the edge.
Here is an example of how you might use the add_edge method to add an edge to your graph:
# Create a graph
graph = Graph([
("a", "b", 2),("a", "c", 5),
("a", "d", 2),("b", "c", 3),
("b", "e", 1),("c", "e", 1),
("c", "h", 1),("c", "f", 1),
("c", "d", 3),("d", "g", 2),
("e", "i", 7),("f", "h", 3),
("f", "g", 2),("h", "i", 1)])
# Add an edge to the graph
graph.add_edge("i", "j", 4)
If you want to add multiple edges to your graph using a for-loop, you can use the add_edge method inside the for-loop to add each edge. Here is an example of how you might do this:
# Create a list of edges to add to the graph
edges = [("i", "j", 4), ("j", "k", 5), ("k", "l", 6)]
# Create a graph
graph = Graph([
("a", "b", 2),("a", "c", 5),
("a", "d", 2),("b", "c", 3),
("b", "e", 1),("c", "e", 1),
("c", "h", 1),("c", "f", 1),
("c", "d", 3),("d", "g", 2),
("e", "i", 7),("f", "h", 3),
("f", "g", 2),("h", "i", 1)])
# Iterate over the edges in the list
for source, destination, weight in edges:
# Add the edge to the graph
graph.add_edge(source, destination, weight)
This should add the edges in the edges list to your graph.