Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first element greater than a given number from a sorted list

I have two lists. List B is like a database to which I need to compare each element of list A, one by one. Lets say

B = [0.6, 1.7, 3, 4.5]
A = [0.6, 0.9, 1.2, 1.5, 2, 2.5, 3, 4, 4.5]

B is a sorted list, so for each A[i] whenever the algorithm finds a number which is >= A[i] in B, it should return that as the output. So my output should look something like:

C = [0.6, 1.7, 1.7, 1.7, 3, 3, 3, 4.5, 4.5]

Could you please suggest me the simplest solution, avoiding nested loops as much as possible?

like image 718
joseph praful Avatar asked Dec 11 '22 04:12

joseph praful


1 Answers

If you can use a 3rd party library, one solution is NumPy via np.searchsorted:

import numpy as np

B = np.array([0.6, 1.7, 3, 4.5])
A = [0.6, 0.9, 1.2, 1.5, 2, 2.5, 3, 4, 4.5]

res = B[np.searchsorted(B, A)]

array([ 0.6,  1.7,  1.7,  1.7,  3. ,  3. ,  3. ,  4.5,  4.5])

This will be more efficient than a sequential loop or an algorithm based on bisect from the standard library.

like image 134
jpp Avatar answered May 18 '23 01:05

jpp