Search code examples
pythonpython-3.xbisection

Using bisect to combine numbers in two lists


In the following two lists

l1 = [10, 33, 50, 67]
l2 = [7, 16, 29, 55]

the goal is to combine the closest numbers in a dict,and the combination have to stop once it reaches the last item in the second list, so in this case if there are items not combined in the first list, these items will not be considered, so the output of the above lists will be

10 -> 7
33 -> 29
50 -> 55
67 ->---   # in this case because the last n. in the first list(55) is identified, so the n.67 will be zero 

this code gives the following output

for s in l1:
    ind = bisect(l2, s, hi=len(l2) - 1)
    ind -= abs(l2[ind-1] - s) < l2[ind] - s
    print("{} -> {}".format(s, l2[ind]))

the output

10 -> 7
33 -> 29
50 -> 55
67 -> 55 ### here is the error, so here will be: 67 -> --, because, 55 is identified in the previous items.

The statement

if ind == len(l2) - 1: 
    break

gives this output

10 -> 7
33 -> 29 

Can someone help?


Solution

  • If all you need is to terminate the loop when the last index of l2 is reached, then simply use break when that condition is met:

    for s in l1:
        ind = bisect(l2, s, hi=len(l2) - 1)
        ind -= abs(l2[ind-1] - s) < l2[ind] - s
        print("{} -> {}".format(s, l2[ind]))
        if ind == len(l2) - 1: break
    

    This produces the output you desire for your sample input:

    >>> for s in l1:
    ...     ind = bisect(l2, s, hi=len(l2) - 1)
    ...     ind -= abs(l2[ind-1] - s) < l2[ind] - s
    ...     print("{} -> {}".format(s, l2[ind]))
    ...     if ind == len(l2) - 1: break
    ... 
    10 -> 7
    33 -> 29
    50 -> 55