如果达到基本情况,为什么这个递归函数永远不会结束?

时间:2016-04-28 01:53:26

标签: python for-loop recursion

所以我试图按照这个Ullmann的算法来解决子图的同构问题,通过在Python上强制它。它说要在找到兼容的矩阵时停止算法,但我的代码会继续打印发现的其余矩阵,即使它到达基本情况。我做错了什么?

recurse(used_columns, cur_row, G, P, M)
    if cur_row = num_rows(M)
        if  M is an isomorphism:
            output yes and end the algorithm

    for all unused columns c
        set column c in M' to 1 and other columns to 0
        mark c as used
        recurse(used_column, cur_row+1, G, P, M')
        mark c as unused

    output no 

这是我编码的方式:

def permute(m0,row,h,g):
    if(row==len(m0)-1):
        n=0
        for i in range(len(m0[0])):
            for j in range(len(m0)):
                n+=m0[j][i]
            if(n>1):
                return
            n=0
        res=[[sum(a*b for a,b in zip(m0_row,h_col)) for h_col in zip(*h)] for m0_row in m0]
        resTr=[[res[j][i] for j in range(len(res))] for i in range(len(res[0]))]
        arr=[[sum(a*b for a,b in zip(m0_row,resTr_col)) for resTr_col in zip(*resTr)] for m0_row in m0]
        for row in arr:
            print(row)
        if(g==arr):
            print("YES!")
            return
    for n in range(len(m0[0])):
        m0[row][n]=0
    for n in range(len(m0[0])):
        m0[row][n]=1 #mark c as used
        permute(m0,row+1,h,g)      
        m0[row][n]=0 #mark c as unused
    print("No")
    return

这是输出:

[0, 0, 1]

[0, 0, 1]

[1, 1, 0]

YES!

[0, 0, 1]

[0, 0, 1]

[1, 1, 0]

YES!

No

No

[0, 0, 1]

[0, 0, 1]

[1, 1, 0]

YES!

[0, 0, 1]

[0, 0, 1]

[1, 1, 0]

YES!

No

[0, 0, 1]

[0, 0, 1]

[1, 1, 0]

YES!

[0, 0, 1]

[0, 0, 1]

[1, 1, 0]

YES!

No

No

我只想打印第一次出现并实际停止,并在没有找到相同的矩阵时打印“否”。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

你没有任何退出条件。 Python并不关心你打印的#34;是的!"所以利用返回值变得必要。算法完成后应返回True,否则返回False。此外,当函数调用自身(最终的for循环)并传递True值时,您必须检查此值,因此它会立即停止:

def permute(m0,row,h,g):
    if(row==len(m0)-1):
        n=0
        for i in range(len(m0[0])):
            for j in range(len(m0)):
                n+=m0[j][i]
            if(n>1):
                return False
            n=0
        res=[[sum(a*b for a,b in zip(m0_row,h_col)) for h_col in zip(*h)] for m0_row in m0]
        resTr=[[res[j][i] for j in range(len(res))] for i in range(len(res[0]))]
        arr=[[sum(a*b for a,b in zip(m0_row,resTr_col)) for resTr_col in zip(*resTr)] for m0_row in m0]
        for row in arr:
            print(row)
        if(g==arr):
            print("YES!")
            return True
    for n in range(len(m0[0])):
        m0[row][n]=0
    for n in range(len(m0[0])):
        m0[row][n]=1 #mark c as used
        if permute(m0,row+1,h,g): #exit when finished
            return True     
        m0[row][n]=0 #mark c as unused
    print("No")
    return False

或者,如果您希望稍后在程序中使用输出;您可以返回该变量而不是True,将值传递下来,否则返回None。更改将是次要的,新的最终for循环将变为:

for n in range(len(m0[0])):
    m0[row][n]=1 #mark c as used
    out=permute(m0,row+1,h,g)
    if out: #exit when finished
        return out
    m0[row][n]=0 #mark c as unused