0
1

More than 3 years have passed since last update.

[python][c++]逆順(降順)リストにbisect(*_bound)をする

Last updated at Posted at 2019-11-14

bisectは降順リストに対応してないので作ってみた。
https://codeday.me/jp/qa/20190215/252510.html
もあるけど自力実装するのもなんだかなと。

from bisect import*

cargo=[1,4,6,43,7,3,6,3,7,32]
length=len(cargo)
cargo_ascending =[1,3,3,4,6,6,7,7,32,43]
cargo_descending=[43,32,7,7,6,6,4,3,3,1]

#cargo_descending引数にとる必要ないんだけど一応
def bisect_reverse_right(cargo_descending,x,lb=0,ub=length):  
    return length-bisect_left(cargo_ascending,x,length-ub,length-lb)

def bisect_reverse_left(cargo_descending,x,lb=0,ub=length):
    return length-bisect_right(cargo_ascending,x,length-ub,length-lb)

print(bisect_left(cargo_ascending,7))  #6
print(bisect_right(cargo_ascending,7))  #8
print(bisect_left(cargo_ascending,43))  #9
print(bisect_right(cargo_ascending,43))  #10

print(bisect_reverse_left(cargo_descending,7))  #2
print(bisect_reverse_right(cargo_descending,7))  #4
print(bisect_reverse_left(cargo_descending,43))  #0
print(bisect_reverse_right(cargo_descending,43))  #1
int bisect_reverse_left(vector<int>cargo_descending,int x,int lb=0,int ub=length){
    return length-(upper_bound(cargo_ascending.begin()+length-ub,cargo_ascending.begin()+length-lb,x)-cargo_ascending.begin());
}
int bisect_reverse_right(vector<int>cargo_descending,int x,int lb=0,int ub=length){
    return length-(lower_bound(cargo_ascending.begin()+length-ub,cargo_ascending.begin()+length-lb,x)-cargo_ascending.begin());
}

コメントをいただいたので比較関数を使った版を

#include <algorithm>
#include <iostream>
#include <vector>

int length;

//こちらはcargo_descendingだけ必要
int bisect_reverse_left(std::vector<int>cargo_descending,int x,int lb=0,int ub=length){
    return *std::upper_bound(cargo_descending.begin()+lb,cargo_descending.begin()+ub, x, [](auto a, auto b) { return a > b; });
}
int bisect_reverse_right(std::vector<int>cargo_descending,int x,int lb=0,int ub=length){
    return *std::lower_bound(cargo_descending.begin()+lb,cargo_descending.begin()+ub, x, [](auto a, auto b) { return a > b; });
}



int main() {
    std::vector<int> v = {5, 4, 3, 2, 2, 1};
    length=v.size();
    std::cout<<bisect_reverse_left(v,3)<<std::endl;  //2
    std::cout<<bisect_reverse_right(v,3)<<std::endl;  //3
}
0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1