函数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}}。
答案 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”。