【发布时间】:2021-08-03 23:37:25
【问题描述】:
我需要在矩阵中找到给定字符串的所有出现,并返回每个出现的字母所在的位置。这些输入的格式示例如下:
soup = ["LAMXB","AOEYF","FCHTB","GFKAR","POSFD"]
text = "HOLA"
其中text 是一个字符串,soup 是一个字母矩阵。
为此,我有以下代码:
def valid_move(x, y, path, cant_row, cant_col):
if (0<=x<=cant_row-1) and (0<=y<=cant_col-1) and ((x,y) not in path):
return True
else:
return False
def busqueda(soup, text, row, col, path, index):
soluciones = []
cant_row = len(soup)
cant_col = len(soup[0])
if soup[row][col] != text[]:
return
if indice == len(text)-1:
for pos_index in range(0,len(path)):
soluciones.append(path[pos_index])
soluciones.append((row,col))
return soluciones
path.append((row,col))
for move in range(8):
if valid_move(row+next_row[move],col+next_col[move],path,cant_row,cant_col):
return busqueda(soup,text,row+next_row[move],col+next_col[move],path,index+1)
path.pop()
def encontrar_ocurrencias(soup,text):
cant_row = len(soup)
cant_col = len(soup[0])
next_row = [-1,-1,-1,0,0,1,1,1]
next_col = [-1,0,1,-1,1,-1,0,1]
path = []
for i in range(0,cant_row):
for j in range(0,cant_col):
busqueda(soup,text,i,j,path,0)
'''
我遇到的问题是它返回None 而不是列表soluciones,这是我需要的输出。
在这种特殊情况下,我想要的输出是
[[(2,2),(1,1),(0,0),(0,1)],[(2,2),(1,1),(0,0),(1,0)]]
如果我使用print(soluciones) 而不是return soluciones,我会得到上面的列表(因此代码有效),但如果我使用return,我会得到None
我已阅读此页面中提出的类似问题,但我仍然找不到答案。我知道每次调用递归函数时都必须使用return,但我仍然看不到我犯的错误在哪里。
提前感谢您的帮助
【问题讨论】:
-
从递归函数返回时,所有路径都需要将结果返回到调用堆栈。如果在完成递归的过程中遇到了裸露的
return,那么在此之前找到的任何结果都将丢失。
标签: python recursion return nonetype