Find if a number exists between a range of numbers specified by a list

Question:

I have a list:

timestamp_list = ['1377091800', '1377093000', '1377094500', '1377095500']

Target number:

ptime = 1377091810

I want to find between which pair of timestamp does ptime lie in. For e.g. in this case, it lies between the first and the second timestamp. So I want to return the value 1377091800 as the desired output.
Similarly, if ptime was 1377091520, then I want the third timestamp to be returned i.e. 1377091500 since it lies between third and the fourth timestamp.

My code:

timestamp_list = ['1377091800', '1377093000', '1377094500', '1377095500']
ptime = 1377091810
for idx, value in enumerate(timestamp_list):
    val = long(value)
if idx!= len(timestamp_list)-1 and ptime >= val and ptime < long(timestamp_list[idx+1]):
    target = val
    break
elif (idx == len(timestamp_list)-1) and ptime >= val:
    target = val
else:
    pass
print target

Output:
1377091800

I wanted to know is there any elegant solution to this? Since I am just starting with python, I am not yet familiar with all the functions in python.

Asked By: Geekster

||

Answers:

Since the timestamps are sorted, you can use bisect for that:

In [24]: timestamp_list = [1377091800, 1377093000, 1377094500, 1377095500]

In [25]: timestamp_list[bisect.bisect_right(timestamp_list, 1377093100)]
Out[25]: 1377094500

(I’ve converted the strings to integers to keep the code clear.)

Answered By: NPE
import bisect
timestamp_list = ['1377091800', '1377093000', '1377094500', '1377095500']
ptime = str(1377093110)
if ptime in timestamp_list:
    target = ptime
else:
    index = bisect.bisect_right(timestamp_list, ptime)-1
    target = timestamp_list[index]
print target

gives the following output:

1377093000

This answer was posted as an edit to the question Find if a number exists between a range of numbers specified by a list by the OP Geekster under CC BY-SA 3.0.

Answered By: vvvvv
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.