-2

Suppose I have a sorted array of integers say

partition = [0, 3, 7, 12, 18, 23, 27]

and then given a value

value = 9

I would like to return the interval on which my value sits. For example

bounds = function(partition, value)
print(bounds)
>>>[7,12]

Is there a function out there that might be able to help me or do I have to build this from scratch?

  • A binary search will quickly return the needed bounds. There are various binning functions that will do this, but I suspect that the extra set-up for that might be harder for others to read than the binary search. – Prune Apr 09 '19 at 21:25
  • Why the down votes? I realize this is probably silly for you Python wonks out there, but I am learning as I go for a project at work. This was a specific syntax question I had no familiarity with in Python. – Laars Helenius Apr 15 '19 at 21:31

3 Answers3

1

Try numpy.searchsorted(). From the documentary:

Find indices where elements should be inserted to maintain order.

import numpy as np
partition = np.array( [0, 3, 7, 12, 18, 23, 27] )
value = 9
idx = np.searchsorted(partition,value)
bound = (partition[idx-1],partition[idx])
print(bound)
>>>>(7,12)

The advantage of searchsorted is that it can give you the index for multiple values at once.

emilaz
  • 1,722
  • 1
  • 15
  • 31
1

The bisect module is nice for doing this efficiently. It will return the index of the higher bound.

You'll need to do some error checking if the value can fall outside the bounds:

from bisect import bisect
partition = [0, 3, 7, 12, 18, 23, 27]
value = 9
top = bisect(partition, value)

print(partition[top-1], partition[top])
# 7 12
Mark
  • 90,562
  • 7
  • 108
  • 148
0
 def function(partition,value):
  for i in range(len(partition)):
  if partition[i]<value and partition[i+1]>value:
    print [partition[i],partition[i+1]]
 partition = [0, 3, 7, 12, 18, 23, 27,5,10]
 value=9
 function(partition,value)
Bharath
  • 113
  • 1
  • 1
  • 10
  • 1
    This is not the optimal solution, since in worst-case, you'd need to touch every element at least once. If you're going to implement it yourself, you're better off doing binary search: https://en.wikipedia.org/wiki/Binary_search_algorithm – emilaz Apr 09 '19 at 22:05