加权有向图的构建python
时间: 2023-09-03 11:15:45 浏览: 96
python由邻接矩阵生成无/有向图.py
构建加权有向图可以使用Python中的字典和列表来实现。
首先,创建一个空的字典来存储图的边和它们的权重,以及一个列表来存储所有节点。
```python
graph = {}
nodes = []
```
然后,可以通过添加节点和边来填充图。添加节点可以直接将节点添加到节点列表中,添加边则需要将边和它们的权重添加到图字典中。
```python
# 添加节点
def add_node(node):
if node not in nodes:
nodes.append(node)
graph[node] = {}
# 添加边
def add_edge(start, end, weight):
if start not in nodes:
nodes.append(start)
graph[start] = {}
if end not in nodes:
nodes.append(end)
graph[end] = {}
graph[start][end] = weight
```
最后,可以打印出图的邻接表来查看图的结构。
```python
# 打印邻接表
def print_graph():
for node in nodes:
edges = []
for neighbor in graph[node]:
edges.append((neighbor, graph[node][neighbor]))
print(f"{node}: {edges}")
```
完整代码如下:
```python
graph = {}
nodes = []
# 添加节点
def add_node(node):
if node not in nodes:
nodes.append(node)
graph[node] = {}
# 添加边
def add_edge(start, end, weight):
if start not in nodes:
nodes.append(start)
graph[start] = {}
if end not in nodes:
nodes.append(end)
graph[end] = {}
graph[start][end] = weight
# 打印邻接表
def print_graph():
for node in nodes:
edges = []
for neighbor in graph[node]:
edges.append((neighbor, graph[node][neighbor]))
print(f"{node}: {edges}")
# 示例
add_node("A")
add_node("B")
add_node("C")
add_edge("A", "B", 2)
add_edge("B", "C", 3)
add_edge("C", "A", 1)
print_graph()
```
输出:
```
A: [('B', 2)]
B: [('C', 3)]
C: [('A', 1)]
```
阅读全文