在列表词典中查找周期
我有一个ID的Python词典。每个ID都有其引用的其他一组其他ID。我如何在字典中找到循环引用?
我的字典的一个示例是:
{1: [3], 2: [1], 3: [2, 4], 4: [2, 3]}.
每个ID键的值是它引用的其他ID的列表,它们无法自行引用。
因此,如果有循环参考,输出将是:
{3, 4 , 3}.
我正在努力弄清楚如何解决这个问题,因为这似乎是一个常见的问题!非常感谢您提供帮助的任何人。
I have a python dictionary of ids. Each id has a set of other ids to which it references. How can I find circular references within the dictionary?
An example of my dictionary is:
{1: [3], 2: [1], 3: [2, 4], 4: [2, 3]}.
The value of each id key is a list of the other ids it references and they can't reference themselves.
So the output, if there were a circular reference, would be:
{3, 4 , 3}.
I'm struggling to figure out how to go about this as it seems like it would be a common problem! Thank you very much for anyone that helps.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NetworkX
库可以在图表中找到周期。您需要实例化有向图,因为ID之间的链接是单向的。您的图中有多个周期。例如,3转为4和4分为3。这也被认为是一个周期。The
networkx
library can find cycles in your graph. You will need to instantiate a directed graph, because your links between IDs are one-way. You have multiple cycles in your graph. For instance, 3 goes to 4 and 4 goes to 3. That is also considered a cycle.如果您仅查找长度为2的循环引用,则仅适用于对(i,j),以便我参考j和j引用i,然后下面的代码可行:
输出:
上面的程序如下:对于每个键i i在字典中,如果我引用j,请检查j是否也引用了i(即我是否也在d [j]中),如果是,则打印i和j。您只有在i< J,为了不打印每个周期两次。
如果您还要打印较大长度的圆形引用(例如i引用j,j引用k和k引用i时),则可以用edge set {(i,j)构造有向图:我参考j} ,并运行算法(例如 Johnson的算法) Digraph。
If you are looking for circular references of length only 2, i.e. only for pairs (i,j) such that i references j and j references i, then the code below works:
Output:
The program above does the following: for each key i in the dictionary, if i references j, then check whether j also references i (i.e. whether i is also in d[j]), and if so, print i and j. You can augment the program to store (or print) (i,j) only if i < j, in order to not print each cycle twice.
If you want to also print circular references of larger lengths (such as when i references j, j references k, and k references i), then you can construct a directed graph with edge set {(i,j): i references j}, and run an algorithm (such as Johnson's algorithm) to find all elementary cycles in a digraph.