Python 递归与渗流
我正在尝试编写一个函数来检查numpy数组中的无向渗流。在这种情况下,当液体可以沿着某种路径(液体可以向上、向下和侧向移动,但不能沿对角线移动)流动时,就会发生无向渗流。下面是一个可以提供给我们的数组示例Python 递归与渗流,python,arrays,numpy,recursion,Python,Arrays,Numpy,Recursion,我正在尝试编写一个函数来检查numpy数组中的无向渗流。在这种情况下,当液体可以沿着某种路径(液体可以向上、向下和侧向移动,但不能沿对角线移动)流动时,就会发生无向渗流。下面是一个可以提供给我们的数组示例 1 0 1 1 0 1 0 0 0 1 1 0 1 0 0 1 1 1 0 0 1 0 1 0 1 这种情况下的渗流结果如下 1 0 1 1 0 1 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 0 0 def flow_from(sites,full,
1 0 1 1 0
1 0 0 0 1
1 0 1 0 0
1 1 1 0 0
1 0 1 0 1
这种情况下的渗流结果如下
1 0 1 1 0
1 0 0 0 0
1 0 1 0 0
1 1 1 0 0
1 0 1 0 0
def flow_from(sites,full,i,j)
n = len(sites)
if j>=0 and j<n and i>=0 and i<n: #Check to see that value is in array bounds
if sites[i,j] == 0:
full[i,j] = 0
else:
full[i,j] = 1
flow_from(sites, full, i, j + 1)
flow_from(sites, full, i, j - 1)
flow_from(sites, full, i + 1, j)
flow_from(sites, full, i - 1, j)
在上面的场景中,液体可以沿着一条路径流动,当前所有带有1的物体都会重新填充,但位置[1,4]和[4,4]中的1除外
我试图编写的函数从数组的顶部开始,并检查它是否为1。如果是1,则将其写入新数组。我希望它接下来做的是检查刚刚分配的1的上、下、左、右位置
下面是我目前拥有的
1 0 1 1 0
1 0 0 0 0
1 0 1 0 0
1 1 1 0 0
1 0 1 0 0
def flow_from(sites,full,i,j)
n = len(sites)
if j>=0 and j<n and i>=0 and i<n: #Check to see that value is in array bounds
if sites[i,j] == 0:
full[i,j] = 0
else:
full[i,j] = 1
flow_from(sites, full, i, j + 1)
flow_from(sites, full, i, j - 1)
flow_from(sites, full, i + 1, j)
flow_from(sites, full, i - 1, j)
def流量来自(站点、完整、i、j)
n=len(站点)
如果j>=0和j=0,并且i忘记了代码块。这是scipy库中已知解决方案的已知问题。从中调整代码,并假设数据位于名为A
的数组中
from scipy.ndimage import measurements
# Identify the clusters
lw, num = measurements.label(A)
area = measurements.sum(A, lw, index=np.arange(lw.max() + 1))
print A
print area
这使得:
[[1 0 1 1 0]
[1 0 0 0 1]
[1 0 1 0 0]
[1 1 1 0 0]
[1 0 1 0 1]]
[[1 0 2 2 0]
[1 0 0 0 3]
[1 0 1 0 0]
[1 1 1 0 0]
[1 0 1 0 4]]
[ 0. 9. 2. 1. 1.]
也就是说,它为您标记了所有“集群”,并确定了大小!从这里可以看到标记为3和4的集群的大小为1,这是您想要过滤掉的。这是一种更强大的方法,因为现在您可以过滤任何大小的代码。忘记了代码块。这是scipy库中已知解决方案的已知问题。从中调整代码,并假设数据位于名为A
的数组中
from scipy.ndimage import measurements
# Identify the clusters
lw, num = measurements.label(A)
area = measurements.sum(A, lw, index=np.arange(lw.max() + 1))
print A
print area
这使得:
[[1 0 1 1 0]
[1 0 0 0 1]
[1 0 1 0 0]
[1 1 1 0 0]
[1 0 1 0 1]]
[[1 0 2 2 0]
[1 0 0 0 3]
[1 0 1 0 0]
[1 1 1 0 0]
[1 0 1 0 4]]
[ 0. 9. 2. 1. 1.]
也就是说,它为您标记了所有“集群”,并确定了大小!从这里可以看到标记为3和4的集群的大小为1,这是您想要过滤掉的。这是一种更强大的方法,因为现在您可以过滤任何大小的单元格。我猜您不止一次访问单元格,因此进入了无限循环。我猜您不止一次访问单元格,因此进入了无限循环。