Denis
Denis

Reputation: 3707

How to count elements between two values in sorted list?

I have a sorted list. For example, my list is:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Actually, I have list of objects of my class with int property, on which the list is sorted.

I want to calculate number of objects, which have value of this property between two values.

I looking for the following python equivalent.

int main () {
  int myints[] = {10,20,30,30,20,10,10,20};
  std::vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20

  std::sort (v.begin(), v.end());                // 10 10 10 20 20 20 30 30

  std::vector<int>::iterator low,up;
  low=std::lower_bound (v.begin(), v.end(), 20); //          ^
  up= std::upper_bound (v.begin(), v.end(), 20); //                   ^

  std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
  std::cout << "upper_bound at position " << (up - v.begin()) << '\n';

  std::cout << "MY_RESULT IS" << (up - v.begin())  - (low- v.begin()) << '\n';

  return 0;
}

Upvotes: 2

Views: 3855

Answers (1)

HavelTheGreat
HavelTheGreat

Reputation: 3386

I would use the bisect module (as it uses binary search, giving it a O(log n) complexity) to take a bisection of both sides, like so:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

import bisect

def find_ge(a, low, high):
    i = bisect.bisect_left(a, low)
    g = bisect.bisect_right(a, high)
    if i != len(a) and g != len(a):
        return a[i:g]
    raise ValueError

Output:

>>>find_ge(my_list, 3, 6)
[3, 4, 5, 6]

Upvotes: 3

Related Questions