douna1941 2015-04-30 05:13
浏览 73
已采纳

有Python bisect模块的Go模拟吗?

I am looking for an out-of-the-box implementation of Python's bisect module in Go. All that I need is to find a position for inserting an item in a sorted array from the left and from the right.

I know the logic behind the implementation, but I do not want to reinvent the wheel with all of its edge cases.

  • 写回答

1条回答 默认 最新

  • douwo8358 2015-04-30 05:25
    关注

    Yes. sort.Search() is what you want. It takes a length and a comparison function, and returns the first index for which the function returns true. The example in the linked docs includes:

    i := sort.Search(len(data), func(i int) bool { return data[i] >= x })
    

    That sets i to the index of the first value >= x (or to len(data) if no items are >= x), so it's like bisect.bisect_left() in Python. Change it to > to get something like bisect_right.

    The Python functions will also search through a range within a list; to do something similar, you could search a subslice of your slice, and add its starting offset to the index Search returns if you need an index into the original slice. There are other ways, but that seems simple and readable.

    Though this is also true of Python lists, insertion into a sorted slice is O(n), i.e., it averages twice as slow on twice as much data. That's still fine for many purposes (many times you have a small list or few inserts), but of course you can't scale indefinitely that way. If you're inserting a ton of items, like a significant fraction of the list size, you could append them all, then sort. For general sorted collections with logarithmic-time inserts, deletes, etc., there's always, for example, github.com/cznic/b, or any number of database-y things.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度