gpt4 book ai didi

python 函数不返回列表

转载 作者:行者123 更新时间:2023-11-30 23:39:46 26 4
gpt4 key购买 nike

我不明白为什么我的反向 Cuthill–McKee 算法的实现会返回在错误的地方。基本上,它会产生正确的结果,但是当我运行代码时,它返回不同的值。

这是带有图表的完整代码,有人可以解释一下这种行为吗?

import numpy as np

A=np.diag(np.ones(8))

nzc=[[4],[2,5,7],[1,4],[6],[0,2],[1,7],[3],[1,5]]

for i in range(len(nzc)):
for j in nzc[i]:
A[i,j]=1

# define the Result queue
R = ["C"]*A.shape[0]


def getDegree(Graph):
"""
find the degree of each node. That is the number
of neighbours or connections.
(number of non-zero elements) in each row minus 1.
Graph is a Cubic Matrix.
"""
degree = [0]*Graph.shape[0]
for row in range(Graph.shape[0]):
degree[row] = len(np.flatnonzero(Graph[row]))-1
return degree

# find the starting point, the parent
degree = getDegree(A)

adj = getAdjcncy(A)
degree2=degree[::]
adj2 = adj[::]
digar=np.array(degree2)
pivots = list(np.where(digar == digar.min())[0])

def main_loop2(deg,start, adj,R):
degcp=deg[:]
digar=np.array(deg)
# use np.where here to get indecies of minimums
if start not in R:
R.append(start)
degcp.pop(start)
if start in pivots:
pivots.pop(start)
print "p: ", pivots
Q=adj[start]
for idx, item in enumerate(Q):
if item not in R:
R.append(item)
print "R", R
print "starts", adj[R[-1]]
Q=adj[R[-1]]
if set(Q).issubset(set(R)) and len(R) < len(degcp) :
print "will now look for new pivot"
p = pivots[0]
pivots.pop(0)
print "pivots", pivots
print "starting with" , p
main_loop2(deg,p,adj,R)
return 'this is never reached'
elif len(R) < len(degcp):
main_loop2(deg,R[-1],adj,R)
return 'wrong'
else:
print "will return R"
print type(R)
return R

inl=[]
Res = main_loop2(degree2,0, adj,inl)

print(Res)

输出:

Degrees: [1, 3, 2, 1, 2, 2, 1, 2]
0
p: [3, 6]
R [0, 4]
starts [0, 2]
R 2 degcp 7
R [0, 4, 2]
starts [1, 4]
R 3 degcp 8
R [0, 4, 2, 1]
starts [2, 5, 7]
R 4 degcp 8
R [0, 4, 2, 1, 5]
R [0, 4, 2, 1, 5, 7]
starts [1, 5]
will now look for new pivot
pivots [6]
starting with 3
R [0, 4, 2, 1, 5, 7, 3, 6]
starts [3]
will return R
<type 'list'>
wrong

所以问题是:
为什么该函数在递归的所有循环中都工作正常,但在最后一个循环中,它返回值 wrong ?输出显示最后一个 else只到达一次,却没有返回列表,我在这里很无奈。如果有人对此有所了解,我将不胜感激。

最佳答案

递归调用的顶层进入此处:

elif len(R) < len(degcp):
main_loop2(deg,R[-1],adj,R)
return 'wrong'

main_loop2 的递归调用中进一步发生的情况并不重要;当它返回时,它将执行return 'wrong'语句。您实际上需要返回最内层调用产生的值,一直返回到顶层 - 这不会神奇地发生在您身上。

您的意思是返回main_loop2(...)吗?

关于python 函数不返回列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13282783/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com