Given boundaries, find interval

后端 未结 1 1734
甜味超标
甜味超标 2020-12-17 02:06

Having a list like this

[207, 357, 470, 497, 537]

where each number denotes the boundary of an interval (0 being implicit at t

1条回答
  •  离开以前
    2020-12-17 02:58

    Using the bisect module of course:

    >>> import bisect
    >>> lst = [207, 357, 470, 497, 537]
    >>> bisect.bisect_left(lst, 0)
    0
    >>> bisect.bisect_left(lst, 360)
    2
    

    The module uses binary search, which requires a sorted sequence. With such a sequence you can divide the sequence in half by picking an index mid-way between the first and last, to see if the value you need is in either half. You then continue dividing the selected half until you found a matching insertion point. That lets you find the insertion point in O(log N) time for a sequence of length N, i.e. very fast.

    0 讨论(0)
提交回复
热议问题