topological sort python recursive and iterative

Define a DAG we need to find a path so that we can follow the path and get the result.

graph={'A':['B','C'],'B':['D','E'],'C':['B','F'],'D':[],'E':[],'F':[]}




def dfs(graph):
	stack=[graph.keys()[0]]
	visit=set()
	while stack:	
		key=stack[-1]
		if graph[key]==[]:
			stack.pop()
			visit.add(key)
		else:
			for val in graph[key]:
				if val in visit:
					graph[key].remove(val)
				else:
					stack.append(val)
	return visit

#print dfs(graph)

def recursive(graph,visit):
	print len(graph),len(visit)
	if len(graph)==len(visit):
		print visit
		return visit
	#print visit
	for key in graph:
		#print key
		if graph[key]==[] and key not in visit:
			visit.add(key)
		else:
			for elem in graph[key]:
				if elem in visit:
					graph[key].remove(elem)
	recursive(graph,visit)

visit=set()
print recursive(graph,visit)

DAG with loop.

loopgraph={'A':['B'],'B':['C','D','E'],'C':['A','F'],'D':[],'E':[],'F':[]}
#print loopgraph.keys()[0]
def check(stack):
	visit={}
	for elem in stack:
		if elem not in visit:
			visit[elem]=1
		else:
			visit[elem]+=1
	count=0
	for key in visit:
		if visit[key]==2:
			count+=1
	if count==len(visit):
		return True
	return False

def findloop(graph):
	stack=[graph.keys()[0]]
	visit=set()
	while stack:
		if check(stack):
			return True
		top=stack[-1]
		if graph[top]==[]:
			stack.pop()
			visit.add(top)
		else:
			for val in graph[top]:
				if val in visit:
					graph[top].remove(val)
				else:
					stack.append(val)
	return False
#print findloop(loopgraph)


can be done with iterative method.



### 拓扑排序算法的 Python 实现 为了实现拓扑排序并应用于文件依赖关系,可以采用基于深度优先搜索(DFS)或者入度计数的方法。以下是利用入度计数方法实现的一个具体例子: #### 基于入度计数的拓扑排序实现 该方法通过计算每个节点的入度,并逐步移除入度为零的节点来构建线性序列。 ```python from collections import deque, defaultdict def topological_sort(graph): # 计算所有节点的入度 in_degree = {node: 0 for node in graph} for node in graph: for neighbor in graph[node]: in_degree[neighbor] += 1 # 初始化队列,加入所有入度为0的节点 queue = deque([node for node in in_degree if in_degree[node] == 0]) result = [] while queue: current_node = queue.popleft() result.append(current_node) # 更新邻居节点的入度 for neighbor in graph[current_node]: in_degree[neighbor] -= 1 if in_degree[neighbor] == 0: queue.append(neighbor) # 如果存在环,则无法完成拓扑排序 if len(result) != len(in_degree): raise ValueError("Graph has at least one cycle; cannot perform topological sort.") return result ``` 上述代码实现了基于入度计数的拓扑排序逻辑[^3]。`graph` 是一个字典形式表示的邻接表,其中键是节点名称,值是一个列表,存储指向其他节点的边。 #### 文件依赖关系的应用实例 假设有一组文件及其依赖关系如下所示: - `fileA` -> `fileB`, 表示 `fileA` 需要在 `fileB` 之后执行。 - `fileC` -> `fileA`. - `fileD` -> `fileB`. 可以用以下方式定义图结构并调用函数: ```python dependencies = { 'fileA': ['fileB'], 'fileB': [], 'fileC': ['fileA'], 'fileD': ['fileB'] } sorted_files = topological_sort(dependencies) print(sorted_files) ``` 运行此程序会返回一个合法的顺序,例如 `[fileB, fileA, fileD, fileC]` 或者类似的排列[^4]。 #### 注意事项 如果输入的图不是有向无环图(DAG),则可能不存在有效的拓扑排序结果。在这种情况下,代码会在最后一步检测到循环的存在并抛出异常。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值