我有一个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;
}
我将使用该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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句