2

私は持っていsorted listます。たとえば、次のmy listとおりです。

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

実際、int propertyリストがソートされているクラスのオブジェクトのリストがあります。

this propertyの間の値を持つオブジェクトの数を計算したいtwo values

次のpythonに相当するものを探しています。

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;
}
4

1 に答える 1

3

bisectモジュールを使用して(バイナリ検索を使用するため、O(log n)の複雑さを与えます)、次のように両側の二等分を取得します。

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

出力:

>>>find_ge(my_list, 3, 6)
[3, 4, 5, 6]
于 2015-03-12T17:14:57.663 に答える