简体   繁体   English

找出两个图形之间的差异

[英]Finding difference between two graphs

I'm solving a sub-problem of mine using a graph data structure.我正在使用图形数据结构解决我的一个子问题。 I have implemented it using dictionaries with vertex as keys and edges as a list of nodes.我已经使用以顶点作为键和边作为节点列表的字典来实现它。 Example:例子:

graph1 = {'1': ['3'],'2': [],'3': ['1', '7'],'7':['3']}

I want to compare two graphs ie, the above graph with:我想比较两个图,即上面的图与:

graph2 = {'1': ['3'],'2': ['3'],'3': ['1', '2'],'7':[]}

The above two graphs are different in terms of edges.以上两个图在边上是不同的。

I want the difference information of these two graphs like:我想要这两个图的差异信息,例如:

graph1-graph2 = {'2':[],'3':['1','7'],'7':['3']}
graph2-graph1 = {'2':['3'],'3':['1','2'],'7':[]}

In short, I'm looking for a symmetric difference between graph1 and graph2.简而言之,我正在寻找图 1 和图 2 之间的对称差异。

I tried getting set difference as suggested in this link.我尝试按照链接中的建议获取设置差异。 But since the values are lists, I'm getting the error TypeError: unhashable type: 'list' .但由于值是列表,我收到错误TypeError: unhashable type: 'list' I understand that this is because the set is immutable and the list is a mutable data structure.我明白这是因为集合是不可变的,而列表是可变的数据结构。 And the type conversion is generating an error.并且类型转换正在产生错误。

I also tried using dataframe difference like given in the this link, I'm getting the same Type error as the above.我还尝试使用链接中给出的数据帧差异,但遇到与上述相同的类型错误。

Is there a simple way of getting the solution?有没有简单的方法来获得解决方案? Any help is appreciated.任何帮助表示赞赏。 Thanks in advance :)提前致谢 :)

PS: I want to keep my graph implementation simple. PS:我想让我的图实现简单。 Hence, I'm not using any advanced libraries like networkx.因此,我没有使用任何像 networkx 这样的高级库。

Edit 1 : Please note, I wanted the results that somewhat resembles the results of symmetric difference of a set and not exactly the symmetric difference.编辑 1 :请注意,我想要的结果有点类似于集合的对称差异的结果,而不是完全对称的差异。

Using the results, I want to understand which all nodes are different in both the graphs.使用结果,我想了解两个图中的所有节点都不同。 The results should contain the nodes whose edge list is different in both the graphs.结果应包含两个图中边列表不同的节点。 Like:喜欢:

'2' : [] (graph1)
'2' : ['3'] (graph2)

and

'3' : ['1','7'] (graph1)
'3' : ['1','2'] (graph2)

You could use the following:您可以使用以下内容:

NB.注意。 this assumes the dictionaries have the same keys (if not, please make the desired output explicit这假设字典具有相同的键(如果没有,请使所需的输出显式

graph1_2 = {}
graph2_1 = {}

for key in graph1:
    s1 = set(graph1[key])
    s2 = set(graph2[key])
    if s1 == s2:
        continue
    else:
        graph1_2[key] = graph1[key]
        graph2_1[key] = graph2[key]

output:输出:

>>> graph1_2
{'2': [], '3': ['1', '7'], '7': ['3']}

>>> graph2_1
{'2': ['3'], '3': ['1', '2'], '7': []}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM