[英]python function not returning a list
我無法弄清楚為什么我的反向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
也只能達到一次,但是,不會返回一個列表,我很無奈的在這里。 如果有人對此有所了解,我將不勝感激。
我發現了另一個關於python和遞歸的問題 ,當我在那里應用解決方案時,我的代碼可以工作!
所以,而不是每個main_loop2(deg,R[-1],adj,R)
我寫retrun main_loop2(deg,R[-1],adj,R)
,現在輸出是:
... snip ...
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'>
[0, 4, 2, 1, 5, 7, 3, 6]
遞歸調用的最高級別進入此處:
elif len(R) < len(degcp):
main_loop2(deg,R[-1],adj,R)
return 'wrong'
無論在main_loop2
的遞歸調用中進一步發生什么都無關緊要; 當它退出時,它將執行return 'wrong'
語句。 你需要實際返回最里面的調用產生的值,一直返回到頂層 - 它不會為你神奇地發生。
你的意思是return main_loop2(...)
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.