Replace loop in python with matlab search equivalent

Suppose I have a sorted array of tuples that is sorted by the first value. I want to find the first index where the condition for the first element of the tuple is satisfied. for example, how to replace the following code

test_array = [(1,2),(3,4),(5,6),(7,8),)(9,10)]
min_value = 5
index = 0
for c in test_array:
        if c[0] > min_value:
           break
        else:
            index = index + 1

With Matlab search equivalent?

i.e. At the end of this cycle, I expect to get 3, but I would like to make it more efficient. I use numpy perfectly for this. I tried using argmax but to no avail.

thank

+1
source share
3 answers

, ( ), bisect ( )

import bisect
test_array = [(1,2),(3,4),(5,6),(7,8),(9,10)]
min_value = 5

print(bisect.bisect_left(test_array,(min_value,10000)))

Hardcoding to 10000 , , , :

print(bisect.bisect_left(test_array,(min_value+1,)))

: 3

floats ( ), sys.float_info.epsilon :

print(bisect.bisect_left(test_array,(min_value*(1+sys.float_info.epsilon),)))

O(log(n)), , for, .

+4

numpy , , argmax(),

import numpy
test_array = numpy.array([(1,2),(3,4),(5,6),(7,8),(9,10)])
min_value = 5

print (test_array[:,0]>min_value).argmax()

, , argmax() nonzero()[0]

0

In general, numpy is whereused in a manner similar to MATLAB find. However, in terms of efficiency, I wherecannot be controlled to return only the first element found. So, from a computational point of view, what you are doing here is no less effective.

the equivalent wherewill be

index = numpy.where(numpy.array([t[0] for t in test_array]) >= min_value)
index = index[0] - 1
0
source

Source: https://habr.com/ru/post/1669312/


All Articles