python - 搜索链接号码的循环

标签 python

我需要从文件中查找循环,该文件的组织方式如下:

28 36

17 43

36 28

43 69

69 17

8 94

在示例中,我想将 [28, 36] 标识为一个列表,因为我有 28 -> 36,然后是 36 -> 28 。出于同样的原因,将 [17, 43, 69] 作为另一个列表。如果循环不闭合,比如上面的8和94,我就不需要它们。

Python 的方法是什么?

最佳答案

这是一个有趣的non trivial任务。不管怎样,Python 的方式是使用一个库。这是使用 networkx 的解决方案

import networkx as nx
from networkx.algorithms.cycles import simple_cycles
g = nx.DiGraph()    
g.add_edges_from([(28, 36), (17, 43), (36, 28), (43, 69), (69, 17), (8, 94)])
print list(simple_cycles(g))

输出

[[28, 36], [69, 17, 43]]

关于python - 搜索链接号码的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37014153/

相关文章:

python - Kivy 和 android 共享首选项

python - Python yaml.load 中遇到 "unacceptable character #x0095: special characters are not allowed in "<unicode string >", position 268"错误

python - 将非常重复的矩阵添加到 numpy/scipy 中的稀疏矩阵中?

python - Pygame - 计算鼠标点击次数

python - sendmail成功,但python smtplib连接失败

python - 使用 Python 的正则表达式和 BeautifulSoup

python - 同时运行gevent进程和服务器

python - Django 不通过/media/显示图像

python - 从 html 转换为 pdf 的页码 - pdfkit,python/django

python - 系列字符串替换为另一个系列的内容(不使用 apply)