2012-03-05 2 views
-2

목표 : 파이썬으로 작성된 알고리즘의 일부 라인을 의사 코드로 변환하려고합니다.pseudocde에서 약간의 파이썬 라인을 변환

주어진 알고리즘의 목표 :주기가있는 유향 그래프에서 모든주기를 찾습니다.

내가 서있는 곳 : 나는 알고리즘에 대한 이론을 잘 이해하고 있으며, 다른 버전도 혼자서 코딩했지만, 작고 효율적이며 정확한 알고리즘을 작성할 수는 없다.

자료 : stackoverflow

내가 지금까지했던 어떤 : 나는, PHP에서 Tarjan, 다양한 버전의 DFS, Flloyd 등을 코딩 얼마나 많은이에 소요되는 주 충분히 설명 할 수 있지만 불행하게도 그들은 일부 솔루션은 오직 하나 그 (것)들을 더 확장해야한다.

추가 : 저는이 알고리즘을 온라인으로 실행했고 효과적이었습니다. 나는 학교 프로젝트를 위해 그것을 스택해야하고 더 진행할 수 없습니다.

def paths_rec(path,edges): 
    if len(path) > 0 and path[0][0] == path[-1][1]: 
     print "cycle", path 
     return #cut processing when find a cycle 

    if len(edges) == 0: 
     return 

    if len(path) == 0: 
     #path is empty so all edges are candidates for next step 
     next_edges = edges 
    else: 
     #only edges starting where the last one finishes are candidates 
     next_edges = filter(lambda x: path[-1][1] == x[0], edges) 

    for edge in next_edges: 
     edges_recursive = list(edges) 
     edges_recursive.remove(edge) 
     #recursive call to keep on permuting possible path combinations 
     paths_rec(list(path) + [edge], edges_recursive) 


def all_paths(edges): 
    paths_rec(list(),edges) 

if __name__ == "__main__": 
    #edges are represented as (node,node) 
    # so (1,2) represents 1->2 the edge from node 1 to node 2. 
    edges = [(1,2),(2,3),(3,4),(4,2),(2,1)] 
    all_paths(edges) 

이 나는 ​​그것이, 내가 이해가 안 #? 선으로 표시 한에서 의사로 작성 관리해야 무엇 :

는 알고리즘이다. 일단 내가 의사 코드로 그들을 가지고 PHP에서 내가 많이 익숙한 그들을 코드 수 있습니다.

procedure paths_rec (path, edges) 

if size(path) > 0 and path[0][0] equals path[-1][1] 
    print "cycle" 
    for each element in path 
     print element 
    end of for 
    return 
end of if 


if size(edges) equals 0 
    return 
end of if 

if size(path) equals 0 
    next_edges equals edges 
else 
    next edges equals filter(lambda x: path[-1][1] == x[0], edges) #? 
end of else 

for each edge in next_edges 
edges_recursive = list(edges) #? 
edges_recursive.remove(edge)#? 
#recursive call to keep on permuting possible path combinations 
paths_rec(list(path) + [edge], edges_recursive)#? 
+0

어쨌든 나는 적어도 그것에 대해 무언가를 할 수있는 downvoting의 이유를 참조 할 수있다. 나는 이제 더 이상 invloved를 얻는 데 방해가되는 점이 있는지 때때로 궁금해한다. – Melsi

답변

1

라인 next_edges = filter(lambda x: path[-1][1] == x[0], edges) 누구 제 점 edges 이들 에지를 포함하는 새로운리스트를 생성하여 현재 경로의 마지막 요소의 제 포인트와 동일하며,

next_edges = [] 
for x in edges: 
    if path[len(path) - 1][1] == x[0] 
     next_edges.append[x] 

받는 동등 edge 복사본이 제거 될 때, 그리스트 edges

edges_recursive = list(edges) 
edges_recursive.remove(edge) 
변경되지 않도록 라인 가장자리 edges 목록의 새 복사본을 만들 0

paths_rec(list(path) + [edge], edges_recursive)edge이 끝에 추가 된 경로와 edge이 제거 된 새 가장자리 목록이있는 recursive call입니다.

+0

정말 고마워요! – Melsi