[英]Finding the minimum value of an array subject to an index of another array and values from another one
I have a square array called dist
of certain size nxn
, a vector called particion
of size m<n
with indices from 0
to n
, and another one called incidencia
of size m
. 我有一个正方形阵列称为
dist
一定尺寸的nxn
,一个称为矢量particion
的大小m<n
具有索引从0
到n
,另一个称为incidencia
的大小m
。 Everything is stored using NumPy. 一切都使用NumPy存储。
What I want to find is the minimal value of dist
subject to two conditions and catch the argument as a vector. 我想找到的是
dist
在两个条件下的最小值,并将参数作为向量。 This is a rough code from C++ translated into python: 这是从C ++转换为python的粗略代码:
num = len(particion)
a = [100] * 2
mini = dist_max
for i in range(num):
pi = particion[i]
for j in range(num):
pj = particion[j]
if (dist[pi,pj] <= mini) & ((incidencia[i] < 2) & (incidencia[j] < 2)):
mini = dist[pi][pj]
a[0] = i
a[1] = j
I feel that this is not the best way to find the minimum since this function takes too much time to compute, even in C++. 我觉得这不是找到最小值的最佳方法,因为即使在C ++中,此函数也会花费太多时间来计算。 Is there a better way?
有没有更好的办法? A more "python-eske" way?
更“ python-eske”的方式?
I don't know the range of your actual data, so I've generated some random data. 我不知道您实际数据的范围,因此我生成了一些随机数据。
from random import randrange
m, n = 100, 200
dist = [[i+j for j in range(n)] for i in range(n)]
part = [randrange(n) for k in range(m)]
inci = [randrange(9) for k in range(m)]
# keep only items in `part` where corresponding `inci` value < 2
part = [p for p,i in zip(part, inci) if i < 2]
# check dist for all couples in `part` and extract minimal value
d = min(dist[pi][pj] for pi in part for pj in part)
This code gives only the minimal distance. 此代码仅给出最小距离。 If you also need the indices where the min is reached, it is better to switch to
numpy
and use the argmin
function it provides. 如果您还需要达到最小值的索引,则最好切换到
numpy
并使用它提供的argmin
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.