Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

Any help is appreciated.

EDIT:

SOLUTION USED:

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

OUTPUT:

1377093000
like image 854
Geekster Avatar asked Aug 31 '13 19:08

Geekster


1 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.)

like image 175
NPE Avatar answered Nov 04 '22 16:11

NPE