Help us understand the problem. What is going on with this article?

Pythonのbisect_leftとbisect_rightをGo言語でも使いたい

Python3にはbisectというモジュールがあり、この中にはbisect_leftbisect_rightという関数が用意されています。bisect_leftはソート済みの配列を二分探索により探索し、挿入点のうちもっとも左側のものを戻り値とします。bisect_rightはその逆で、挿入点のうち、もっとも右側が戻り値となります。

import bisect

digits = [111, 222, 333, 333, 333, 444, 555]
bisect.bisect_left(digits, 333)  #=> 2
bisect.bisect_right(digits, 333) #=> 5

Go言語でbisect_leftbisect_rightと同じようなことをしたい場合、すなわち、二分探索でもっとも右側の挿入点を探したい、もっとも左側の挿入点を探したい場合、sortパッケージのSearchを利用し、それぞれ次のように実装します。

digits := []int{111, 222, 333, 333, 333, 444, 555}
sort.Search(len(digits), func(i int) bool { return digits[i] >= 333 }) //=> 2
sort.Search(len(digits), func(i int) bool { return digits[i] > 333 })  //=> 5

つまりbisect_leftの場合は不等号で比較、bisect_rightの場合は等号付き不等号で比較すればよいわけです。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした