You can use the bisect module, the worst complexity is O(N * logN) :
import bisect lis1 = [4, 20, 26, 27, 30, 53, 57, 76, 89, 101] lis2 = [17, 21, 40, 49, 53, 53, 53, 53, 70, 80, 81, 95, 99] #this must be sorted #use lis2.sort() in case lis2 is not sorted for x in lis1: #returns the index where x can be placed in lis2, keeping lis2 sorted ind=bisect.bisect(lis2,x) if not (x >= lis2[-1] or x <= lis2[0]): sm, bi = lis2[ind-1], lis2[ind] if sm == x: """ To handle the case when an item present in lis1 is repeated multiple times in lis2, for eg 53 in this case""" ind -= 1 while lis2[ind] == x: ind -= 1 sm = lis2[ind] print "{} <= {} <= {}".format(sm ,x, bi)
exit:
17 <= 20 <= 21 21 <= 26 <= 40 21 <= 27 <= 40 21 <= 30 <= 40 49 <= 53 <= 70 53 <= 57 <= 70 70 <= 76 <= 80 81 <= 89 <= 95
Although this does not output anything for 4 and 101 , since 4 is less than any element in lis2 and 101 is larger than any element in lis2. But this can be fixed if required.
Ashwini chaudhary
source share