Question

Having a sorted list and some random value, I would like to find in which range the value is.

List goes like this: [0, 5, 10, 15, 20] And value is, say 8.

The standard way would be to either go from start until we hit value that is bigger than ours (like in the example below), or to perform binary search.

grid = [0, 5, 10, 15, 20]
value = 8
result_index = 0
while result_index < len(grid) and grid[result_index] < value:
    result_index += 1

print result_index

I am wondering if there is a more pythonic approach, as this although short, looks bit of an eye sore. Thank you for your time!

Was it helpful?

Solution

>>> import bisect
>>> grid = [0, 5, 10, 15, 20]
>>> value = 8
>>> bisect.bisect(grid, value)
2

Edit:

bisect — Array bisection algorithm

OTHER TIPS

for min, max in zip(grid, grid[1:]): # [(0, 5), (5, 10), (10, 15), (15, 20), (20, 25)]
  if max <= value < min: #previously: if value in xrange(min, max):
    return min, max
raise ValueError("value out of range")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top