python中基于对象的图形表示

object based graph representation in python

本文关键字:图形 表示 对象 于对象 python      更新时间:2023-10-16

在斯坦福算法讲座中,拉夫加登教授列出了邻接列表的以下成分:

  1. 顶点数组或列表
  2. 边的阵列或列表
  3. "顶点列表"中的每个顶点都指向与其关联的边
  4. "边列表"中的每条边都指向其边点

如何在python中实现这一点,尤其是3和4的组合?这对我来说是一个挑战。我在C++中用指针做到了这一点。我可以想出一种方法,如果你认为正确的话,请告诉我。数字4可以通过元组列表来实现CCD_ 1或将另一个元素添加到元组中以获得权重值。如何使"顶点列表"指向其上的边?Vertices = {1 : [0,2] 2: [0,1] 3: [1] 4:[3]}这里的"顶点"是一个字典,每个关键点(顶点)的值是包含该关键点("顶点")的边的索引列表。这看起来合理吗?

好的,我也会给出它的C++实现。

struct Node;
struct Arcs; //Forward declarations as each of them references each other
using namespace std
struct SimpleGraph  // Has all the nodes
{
   set<Node *> nodes;
   set<Arc *> arcs;
}
//Node contains node_number and the set of arcs/edges from this node.
struct Node
{  
   int node_number; 
   set<Arc *> arcs;
}
// Arc contains start and finish node and the cost associated with the Arc/Edge
struct Arc
{
  Node* start;
  Node* finish;
  double cost;
}

因为我们在C++中使用指针,Arc信息的变化会自动反映在Node中。缺少指针使得在python中很难做到这一点。所以我尽力做到最好。

在python中,基本上所有东西都是一个对象,因此列表、dicts和映射也是对象,因此可以通过它们的地址进行访问(就像C++在使用引用调用时一样)。

看看下面的代码示例,它表明:

list_a = ['a', 'b', 'c']
list_b = ['d', 'e', 'f']
one_dict = {'entry1': list_a, 'entry2': list_b}
def add_entry(target_list, entry):
    target_list.append(entry)
print("Our example dict:")
print(one_dict)
print("Modifying 'list_a' and 'list_b'.")
list_a[1] = 'B'
list_b[2] = 'F'
print(list_a)
print(list_b)
print("Appending new entries to 'list_a' and 'list_b'")
add_entry(list_a, 'q')
add_entry(list_b, list_a)
print(list_a)
print(list_b)
print("'list_a' and 'list_b' can still being accessed via 'one_dict'.")
print(one_dict)

这是输出,您可以清楚地看到one_dict保存了对这些列表的引用:

Our example dict:
{'entry2': ['d', 'e', 'f'], 'entry1': ['a', 'b', 'c']}
Modifying 'list_a' and 'list_b'.
['a', 'B', 'c']
['d', 'e', 'F']
Appending new entries to 'list_a' and 'list_b'
['a', 'B', 'c', 'q']
['d', 'e', 'F', ['a', 'B', 'c', 'q']]
'list_a' and 'list_b' can still being accessed via 'one_dict'.
{'entry2': ['d', 'e', 'F', ['a', 'B', 'c', 'q']], 'entry1': ['a', 'B', 'c', 'q']}  

因此,实现非常直接,就像您的C++代码一样。