查找 Python 集合中的最小连续整数
获取 Python 集合中最小 N 个连续整数的列表的最佳方法是什么?
>>> s=set([5,6,10,12,13,15,30,40,41,42,43,44,55,56,90,300,500])
>>> s
set([42, 43, 44, 5, 6, 90, 300, 30, 10, 12, 13, 55, 56, 15, 500, 40, 41])
>>> smallest_contiguous(s,5)
[40,41,42,43,44]
>>> smallest_contiguous(s,6)
[]
编辑:谢谢大家的回答。
What is the best way to get a list of the smallest N contiguous integers in a Python set?
>>> s=set([5,6,10,12,13,15,30,40,41,42,43,44,55,56,90,300,500])
>>> s
set([42, 43, 44, 5, 6, 90, 300, 30, 10, 12, 13, 55, 56, 15, 500, 40, 41])
>>> smallest_contiguous(s,5)
[40,41,42,43,44]
>>> smallest_contiguous(s,6)
[]
Edit: Thanks for the answers, everyone.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
斯文的想法是正确的。您只需检查前面的数字 N - 1 即可避免检查超集。
这仅对于作为输入的集合并且知道该集合仅包含整数而言始终是正确的。
Sven has the right idea. You can avoid having to check supersets by just checking the number N - 1 ahead.
This will only always be correct for a set as input and knowing that the set only contains integers.
这个怎么样?
它可能不是最有效的解决方案,但它很简洁。
编辑:贾斯汀的方法也可以变得更简洁:
How about this?
It might not be the most efficient solution, but it is concise.
Edit: Justin's approach could also be made more concise:
应该可以了...在排序列表中向前查看
length - 1
步。由于它仅包含整数并且已排序,因此差值也必须为length - 1
。That should do it ... look ahead
length - 1
steps in the sorted list. Since it contains integers only and is sorted, the difference must belength - 1
as well.这是我想出的一个:
它会修改输入集作为副作用。
Here's one I came up with:
It modifies the input set as a side effect.
itertools 来救援。 groupby 在这里完成所有繁重的工作
由于调用了
sorted()
,该算法的复杂度为 O(n logn)itertools to the rescue. groupby does all the grunt work here
The algorithm is O(n logn) because of the call to
sorted()