【问题标题】:Converting a few python lines in pseudocde用伪代码转换几行 python
【发布时间】:2012-03-05 01:43:55
【问题描述】:

目标:尝试将用 python 编写的算法的某些行转换为伪代码。

给定算法的目标:在有向图中找到所有循环。

我的立场:我很了解算法背后的理论,我自己也编写了不同的版本,但是我不能自己编写一个小、高效和正确的算法。

来源: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)#?

【问题讨论】:

  • 一点也不意外,至少你可以把投反对票的原因告诉我,这样我就可以做点什么了,我真的想知道有时是否还有必要再为被爱而烦恼!

标签: python graph-theory pseudocode


【解决方案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]

这些行创建了边列表edges 的新副本,因此当从该副本中删除edge 时,它不会更改列表edges

edges_recursive = list(edges)
edges_recursive.remove(edge)

paths_rec(list(path) + [edge], edges_recursive) 只是recursive call,路径末尾添加了edge,并删除了edge 的新边列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 2020-07-07
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    相关资源
    最近更新 更多