[英]Dead Kernel on running code in Jupyter Notebook, Python 3
I'm currently writing a short code as follows that returns the co-ordinates and size of the longest path in a grid with the following constraints:我目前正在编写如下短代码,它返回网格中最长路径的坐标和大小,具有以下约束:
My code is as follows:我的代码如下:
import numpy as np
grid = np.random.randint(3, size=(5, 5))
def get_longest_path(grid):
# setup
cols, rows = grid.shape # length, width
# pathfinder function
def pathfinder(i,j):
best, best_path = 0, []
udlr = {(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)} # up down left right directions
for x, y in udlr:
if 0 <= x < cols and 0 <= y < rows and abs(grid[x][y] - grid[i][j]) <= 1: # check it's in bounds
#grid[x][y] > grid[i][j]
n, path = pathfinder(x,y)
if n > best:
best, best_path = n, path
return best + 1, [(i,j)] + best_path
#return longest path
return max(pathfinder(0,j) for j in range(rows))
get_longest_path(grid)
As far as I can tell, it works fine if I use the constraint grid[x][y] > grid[i][j]
in place of abs(grid[x][y] - grid[i][j]) <= 1
.据我所知,如果我使用约束
grid[x][y] > grid[i][j]
代替abs(grid[x][y] - grid[i][j]) <= 1
效果很好abs(grid[x][y] - grid[i][j]) <= 1
。 However, if I run this as it is, the Jupyter kernel dies straight away.但是,如果我按原样运行,Jupyter kernel 会立即死亡。
Perhaps it starts an infinite loop, but I can't see why this would be the case.也许它开始了一个无限循环,但我不明白为什么会这样。
Any advice would be appreciated, thank you.任何建议将不胜感激,谢谢。
try defining pathfinder() outside and above get_longest_path()尝试在 get_longest_path() 之外和之上定义 pathfinder()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.