在包含 1 个以上循环的字典中查找所有循环

如何解决在包含 1 个以上循环的字典中查找所有循环

给定以下循环字典:

{'E': ['F'],'F': ['C','G'],'C': ['E'],'G': ['H'],'H': ['I'],'I': ['J','D'],'J': ['D'],'D': ['E']}

其中键代表父节点,值是它指向的所有子节点(这表示有向图)。

可以看出有3个周期:

  1. E -> F -> C
  2. E -> F -> G -> H -> I -> J -> D
  3. E -> F -> G -> H -> I -> D

我试图找出一种能够提取所有循环的方法或函数,以便我可以输出或返回三个循环:

EFC

EFGHIJD

EFGHID

我正在寻找 Python 解决方案!谢谢:)

解决方法

您可以使用递归生成器函数:

d = {'E': ['F'],'F': ['C','G'],'C': ['E'],'G': ['H'],'H': ['I'],'I': ['J','D'],'J': ['D'],'D': ['E']}
def get_cycles(n,o = None,c = []):
   if n == o: #check if current node being examined is the same as the start
      yield c #if the condition is met,then a cycle is found and the path is yielded back
   else:
      #get the children of the current node from d and iterate over only those that have not been encountered before (except if the node is the same as the start)
      for i in filter(lambda x:x not in c or x == o,d.get(n,[])):
         #recursively find the children of this new node `i`,saving the running path (c + [n])
         yield from get_cycles(i,o = n if o is None else o,c = c + [n])

print(list(get_cycles('E')))
print(list(get_cycles('D')))

输出:

[['E','F','C'],['E','G','H','I','J','D']]
[['D','E','J'],['D','I']]
,

获取一个起始节点的所有周期的一种方法是:

System check identified no issues (0 silenced).
June 15,2021 - 01:54:10
Django version 3.2.4,using settings 'codersavvy.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /api/blogs/post/
Traceback (most recent call last):
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\django\core\handlers\exception.py",line 47,in inner
    response = get_response(request)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\django\core\handlers\base.py",line 181,in _get_response
    response = wrapped_callback(request,*callback_args,**callback_kwargs)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\django\views\decorators\csrf.py",line 54,in wrapped_view
    return view_func(*args,**kwargs)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\django\views\generic\base.py",line 70,in view
    return self.dispatch(request,*args,**kwargs)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\views.py",line 509,in dispatch
    response = self.handle_exception(exc)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\views.py",line 469,in handle_exception
    self.raise_uncaught_exception(exc)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\views.py",line 480,in raise_uncaught_exception
    raise exc
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\views.py",line 506,in dispatch
    response = handler(request,**kwargs)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\decorators.py",line 50,in handler
    return func(*args,**kwargs)
  File "D:\work environment\Django_Api\codersavvy\blog\views.py",line 75,in post_blog
    image=data['image'],KeyError: 'image'
[15/Jun/2021 01:54:15] "POST /api/blogs/post/ HTTP/1.1" 500 96879

使用您的图表和起始节点 def cycles(graph,start): results = [] paths = [(start,)] while paths: path = paths.pop() childs = set(graph.get(path[-1],[])) if start in childs: results.append(path) paths.extend( (path + (child,)) for child in childs.difference(path) ) return results ,您将得到(Eprint(cycles(g,'E')) 您的字典):

g

如果您想要图形中的所有循环,则必须做更多工作:一个起始节点通常不会导致图形的所有循环。实现这一目标的一种方法是遍历所有节点,应用 [('E','D'),('E','C')] ,然后收集所有结果:

cycles
result = [cycle for node in g for cycle in cycles(g,node)]

但是这种方式会导致一些冗余:[('E','C'),('F','D','E'),'C',('C','F'),('G',('H','G'),('I','H'),('J','I'),('D','J')] ('E','C')('C','F')本质上是相同的(等等)。如果你想摆脱它,你可以这样做:

( 'F','E')

results = [] d = {node: set(g.get(node,[])) for node in g} nodes = list(d) while nodes: node = nodes.pop() results.extend(cycles(d,node)) del d[node] for other_node in d: d[other_node].discard(node)

print(results)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res