python中基于对象的图形表示
object based graph representation in python
在斯坦福算法讲座中,拉夫加登教授列出了邻接列表的以下成分:
- 顶点数组或列表
- 边的阵列或列表
- "顶点列表"中的每个顶点都指向与其关联的边
- "边列表"中的每条边都指向其边点
如何在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++代码一样。
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 如何将ampl中的集合表示为c++中的向量
- std::is_base_of表示ctor编译错误
- C++图形类指针混淆
- 输入中的字符串数未知(以字母表示)
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 如何在内核C++中使用1920x1080x16M图形或类似的16M颜色?(VGA)
- 将图形表示为unordered_map<字符串、向量>时拓扑排序错误<string>
- 使用 OpenGL 使用 C++ 以图形方式表示堆积条形图
- 如何从图形的邻接列表表示中随机选择边缘
- 以图形方式表示C++代码
- 如何在 c++ 中表示图形
- 图形的邻接列表表示形式不正确
- python中基于对象的图形表示
- 在c++中使用STL通过邻接表表示图形
- c++中向量与列表的图形表示
- 使用向量<vector>在 C++ 中表示图形
- 使用 unordered_map 实现图形表示的邻接列表
- C/C++ 图形接口,用于表示偏序