python break怎么用_如何在Python中不使用return或break来中断函数

我在节点a和b之间遍历dfs,但是当我在节点b中断循环时,算法继续。这是我的代码: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循环中返回,尝试使用break和try/catch方法。有没有什么好方法可以打破这个函数,或者我必须重写它,因为它不会在u的所有邻域中递归?在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值