Search code examples
pythonarraysminimum

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 n x n, a vector called particionof size m<n with indices from 0 to n, and another one called incidencia of size m. Everything is stored using NumPy.

What I want to find is the minimal value of dist subject to two conditions and catch the argument as a vector. This is a rough code from C++ translated into 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++. Is there a better way? A more "python-eske" way?


Solution

  • 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.