首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Python中脱离函数而不返回或中断

如何在Python中脱离函数而不返回或中断
EN

Stack Overflow用户
提问于 2016-02-26 11:59:35
回答 3查看 3K关注 0票数 3

我在节点a和b之间遍历dfs,但是当我在节点b处中断循环时,算法仍在继续。这是我的代码:

代码语言:javascript
复制
import networkx as nx

def Graph():
    G=nx.Graph()

    k = 30

    G.add_edge(1,2)
    G.add_edge(2,3)
    G.add_edge(1,3)

    for i in range(2,k+1):
        G.add_edge(2*i-2,2*i)
        G.add_edge(2*i-1,2*i)
        G.add_edge(2*i-1,2*i+1)
        G.add_edge(2*i,2*i+1)

    G.add_nodes_from(G.nodes(), color='never coloured')
    G.add_nodes_from(G.nodes(), label = -1)
    G.add_nodes_from(G.nodes(), visited = 'no')

    return G

def dfs(G,a,b,u):
    global i
    G.node[u]['visited'] = 'yes'
    i += 1
    G.node[u]['label'] = i
    print(u)
    print("i", i)
    for v in G.neighbors(u):
        if v == b:
            G.node[v]['visited'] = 'yes'
            i += 1
            G.node[v]['label'] = i
            print("b is ", v)
            print("distance from a to b is ", G.node[v]['label'])
            break### the problem area, doesn't break out the function
        elif v != b:
            if G.node[v]['visited'] == 'no':
                dfs(G,a,b,v)
G=Graph()
a=1
b=19
i = 0
print('Depth-First-Search visited the following nodes of G in this order:')
dfs(G,a,b,a)  ### count the DFS-path from a to b, starting at a
print('Depth-First Search found in G7 a path between vertices', a, 'and', b, 'of length:', G7.node[b]['label'])
print()

我尝试过从for循环中返回,尝试使用中断,还尝试了try/catch方法。是否有任何优雅的方式来打破这个函数,或者我必须重写它,因为它不会通过u的所有邻居进行递归?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-02-26 12:10:52

这里的问题不是breakreturn,而是使用递归,而不是在每个递归调用中停止循环。您需要做的是从dfs函数返回一个结果,该结果告诉您是否找到了节点,如果递归调用找到了,则中断else块内的循环。就像这样:

代码语言:javascript
复制
def dfs(G,a,b,u):
    global i
    G.node[u]['visited'] = 'yes'
    i += 1
    G.node[u]['label'] = i
    print(u)
    print("i", i)
    for v in G.neighbors(u):
        if v == b:
            G.node[v]['visited'] = 'yes'
            i += 1
            G.node[v]['label'] = i
            print("b is ", v)
            print("distance from a to b is ", G.node[v]['label'])
            return True
        elif v != b:
            if G.node[v]['visited'] == 'no':
                found = dfs(G,a,b,v)
                if found:
                    return True
    return False

请注意,这如何将成功的结果传回到整个调用堆栈中。

票数 3
EN

Stack Overflow用户

发布于 2016-02-26 12:14:42

在这种情况下,我经常使用全局标志变量来表示搜索已经完成。例如,path_found

票数 1
EN

Stack Overflow用户

发布于 2016-02-26 12:22:48

如果我理解得很好,你的问题不是你不能退出这个函数。

问题是你没有摆脱递归。有很多方法可以解决这个问题。

这是许多例子之一。通过返回True并在每个调用中检查这一点,您将开始冒泡并跳过递归过程中的每个循环。您可以将真值理解为“找到的路径”

代码语言:javascript
复制
def dfs(G,a,b,u):
    global i
    G.node[u]['visited'] = 'yes'
    i += 1
    G.node[u]['label'] = i
    print(u)
    print("i", i)
    for v in G.neighbors(u):
        if v == b:
            G.node[v]['visited'] = 'yes'
            i += 1
            G.node[v]['label'] = i
            print("b is ", v)
            print("distance from a to b is ", G.node[v]['label'])
            return True
        elif v != b:
            if G.node[v]['visited'] == 'no':
                if dfs(G,a,b,v):
                    return True
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35651147

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档