Python 平分列表
我需要编写一个函数,它接受一个列表并将其平分(就像 bisect 模块一样,但我不能使用它)。我通常会展示到目前为止我所做的事情,但我真的不知道如何在没有模块的情况下做到这一点,所以我希望有人可以帮助我一点。这是我需要弄清楚的确切问题:
编写一个名为 bisect 的函数,它接受一个排序列表和一个目标值,并返回列表中值的索引(如果存在),如果不存在则返回 None
I need to write a function that takes a list and bisects it (like the bisect module but I cannot use that). I normally would show what I have done so far but I really do not know how to do it without the module so I am hoping someone can help me out a bit. Here is the exact question I need to figure out:
Write a function called bisect that takes a sorted list and a target value and returns the index of the value in the list, if it’s there, or None if it’s not
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我正在做“think python”第 10 章练习 8 中的作业,我厌倦了上面由 fred 编写的代码。它似乎有一些错误。
1. 计数器不适用于包含 100k 字符串的长列表
2. 有时,对于我确定在列表中的内容,它会返回 None 。
所以我稍微调整了一下:
这是我的版本:
它工作得很好,它使用来自 swampy 2.0 的单词列表进行了测试,名为 Words.txt,该单词表最初来自 moby 集合:113809of.fic
希望这可以帮助那些苦苦挣扎的人使用二等分程序
如果大师可以帮助我纠正这个缺陷,那就太好了,谢谢,
i was doing the homework from "think python" chapter 10 exercise 8 and i tired the code above written by fred. it seems to have some bugs.
1. the counter doesn't work for long list with 100k strings
2. sometimes it returns None for things that i'm sure is in the list.
so i tweaked it a little bit:
this is my version:
it works very well, it tested it with a wordlist from swampy 2.0 named words.txt, which originally comes from the moby collection: 113809of.fic
hope this helps those of you struggling with the bisect program
Also will be great if a guru can help me correct that flaw, thanks,
bisect 模块跟踪列表并保持其排序,而不必每次插入元素时都重新排序。您需要实现的方法只需要在排序列表中进行搜索。
这基本上是进行二分搜索。
在递归循环中进一步调用时,传递索引以跟踪原始列表的索引。
The bisect module keeps track of a list, keeping it sorted, without having to resort every time you insert an element. The method you need to implement just needs to search inside a sorted list.
this basically does a binary search.
The indexes are passed to keep track of the indexes of the original list, in invocations further down the recursion loop.