sách gpt4 ăn đã đi

So sánh "đẳng cấu" của các đối tượng Đồ thị NetworkX thay vì so sánh 'địa chỉ' mặc định

In lại 作者:太空狗 更新时间:2023-10-30 01:22:38 27 4
mua khóa gpt4 giày nike

我想使用 NetworkX Graph 对象作为 Python từ điển 中的键。但是,我不希望默认的比较行为(即通过对象的地址)。相反,我希望同构图是 từ điển 中相同元素的键。

此行为是否已在某处实现?我找不到这方面的任何信息。

如果我必须自己实现,以下评估是否现实?

  • Sẽ networkx.Graph 包装在一个类中。
  • sự định nghĩa __eq__ 使其调用 is_isomorphic
  • 以某种方式定义 __hash__(欢迎提出建议)。

我想我必须让这个包装图不可变,because :

If a class defines mutable objects and implements an __eq__() method, it should not implement __hash__(), since the implementation of hashable collections requires that a key’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).

câu trả lời hay nhất

这是一个子类化 networkx Graph 并按照您的描述添加 cân bằngbăm 函数的示例。我不确定它是否能解决您的问题,但应该是一个开始。

import networkx as nx

class myGraph(nx.Graph):
def __eq__(self, other):
return nx.is_isomorphic(self, other)
def __hash__(self):
return hash(tuple(sorted(self.degree().values())))


nếu __name__ == '__main__':
G1 = myGraph([(1,2)])
G2 = myGraph([(2,3)])
G3 = myGraph([(1,2),(2,3)])
print G1.__hash__(), G1.edges()
print G2.__hash__(), G2.edges()
print G3.__hash__(), G3.edges()
print G1 == G2
print G1 == G3
graphs = {}
graphs[G1] = 'G1'
graphs[G2] = 'G2'
graphs[G3] = 'G3'
print graphs.items()

输出类似:

3713081631935493181 [(1, 2)]
3713081631935493181 [(2, 3)]
2528504235175490287 [(1, 2), (2, 3)]
ĐÚNG VẬY
SAI
[(<__main__.myGraph object at 0xe47a90>, 'G2'), (<__main__.myGraph object at 0x1643250>, 'G3')]
[aric@hamerkop tmp]$ python gc.py
3713081631935493181 [(1, 2)]
3713081631935493181 [(2, 3)]
2528504235175490287 [(1, 2), (2, 3)]
ĐÚNG VẬY
SAI
[(<__main__.myGraph object at 0x1fefad0>, 'G2'), (<__main__.myGraph object at 0x27ea290>, 'G3')]

关于python - NetworkX Graph 对象的“同构”比较,而不是默认的 'address' 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20530455/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress