返回语句后循环继续,如何停止

时间:2019-05-14 17:08:38

标签: python function loops return continue

函数next_c在到达return True之后继续运行,然后稍后返回none

我已经在各处放置了打印语句,以查找正在运行的内容。 if语句中的“ Check 1”正好在return语句打印之前,然后else语句紧随其后运行。 如果将return True放在问题if语句之前,则可以得到程序其余部分的预期结果。

import numpy as np

A=[ ["I","L","A","W"],
  ["B","N","G","E"],
  ["I","U","A","O"],
  ["A","S","R","L"] ]



def next_c(atemp, x, y, word): #make a subarray from atemp and check to next c
    suba = atemp[x-1:x+2:,y-1:y+2:]
    for n in range(3):
        for m in range(3):
            if word[0] == suba[n][m]:
#here is the problem
                if len(word) == 1:
                    print("Check1")
                    return True
                else:
                    #change temp array char to 0 then get new sub array coords
                    atemp[x][y] = 0
                    x = x + n -1 
                    y = y + m -1
                    next_c(atemp, x, y, word[1:])


def look(atemp, word, size):#look for 1st c in temp array
    for x in range(size+1):
        for y in range(size+1):
            if atemp[x][y]==word[0]:
                atemp[x][y] = 0  #replace letter with a 0 
#this should return True but always gets None
                if next_c(atemp, x, y, word[1:]):
                    print("Check2")
                    return True

def find_word(board, word):
    a = np.array(board)
    a = np.pad(a, 1, "constant")
    if look(a, word, len(board)):
        return True
    return False

print(find_word(A, "BINGO")) #this should be True

print('Check1')之后,我希望返回语句True进入if next_c(atemp, x, y, word[1:]):,以便执行print('Check2'),然后从{{ 1}}。

1 个答案:

答案 0 :(得分:0)

您忽略了跟踪您的递归。试试这个入门:

            if len(word) == 1:
                print("Check1")
                return True
            else:
                #change temp array char to 0 then get new sub array coords
                atemp[x][y] = 0
                x = x + n -1 
                y = y + m -1
                print("Check 2: before recur")
                next_c(atemp, x, y, word[1:])
                print("Check 3: after  recur")

输出:

Check 2: before recur
Check 2: before recur
Check 2: before recur
Check1
Check 3: after  recur
Check 3: after  recur
Check 3: after  recur
Check 2: before recur
Check 3: after  recur
False

问题是您无法返回除基本情况True之外的任何布尔值。您击中“ Check1”点并返回True,但是下一次调用堆栈时将忽略返回值。这意味着对于除简并的情况以外,next_c返回None(默认返回值),这就是传递回look,然后传递给find_word的原因。 None是一个“假”值,因此find_word将该值转换为主程序接收的显式False

在该递归调用上放置所需的return。然后我们得到:

Check 2: before recur
Check 2: before recur
Check 2: before recur
Check1
Check2
True

请注意,程序如何不再脱离最里面的else块的末尾-因为代码刚好返回,所以永远不会出现“检查3”。