生成具有重复元素的列表的排列
在 Python 中,使用 itertools 模块生成列表的所有排列非常简单。我遇到的情况是,我使用的序列只有两个字符(即 '1122'
)。我想生成所有独特的排列。
对于字符串 '1122'
,有 6 种独特的排列(1122
、1212
、1221
等),但 itertools.permutations
将产生 24 个项目。仅记录独特的排列很简单,但收集它们所需的时间会比需要的时间长得多,因为要考虑所有 720 个项目。
是否有一个函数或模块可以在生成排列时考虑重复元素,这样我就不必编写自己的元素?
In Python, it is quite simple to produce all permutations of a list using the itertools
module. I have a situation where the sequence I'm using only has two characters (i.e. '1122'
). I want to generate all unique permutations.
For the string '1122'
, there are 6 unique permutations (1122
, 1212
, 1221
, etc), but itertools.permutations
will yield 24 items. It's simple to only record the unique permutations, but it will take much longer than necessary to collect them as all 720 items are considered.
Is there a function or module that accounts for repeated elements when generating permutations so I don't have to write my own?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
此网页看起来很有希望。
2017-08-12
七年后,这是一个更好的算法(为了清晰起见):
This web page looks promising.
2017-08-12
Seven years later, here is a better algorithm (better for clarity):
更多 Itertools 有这样的功能:
安装:
More Itertools has a function for this:
Installation:
这也是一个常见的面试问题。在标准库 modules 无法使用的情况下,这里是一个实现考虑:
输出:
您可以使用 join< 将输出从可变列表转换为字符串/a> 在这一行:
得到:
This is also a common interview question. In the event standard library modules can't be used, here is an implementation to consider:
Output:
You can transform the output from the mutable list to string using join on this line:
to get:
输出:
Output:
一个非常简单的解决方案,可能类似于
more_itertools
使用的解决方案,它利用 @Brayoni,可以通过构建可迭代的索引来完成。假设您有
L = '1122'
。您可以使用如下方式构建一个非常简单的索引:假设您有
L
的排列P
。P
有多少个元素并不重要。字典顺序规定,如果将P
映射到使用索引,它必须始终增加。像这样映射P
:现在您可以丢弃小于或等于目前看到的最大值的元素:
请注意,除了保留最后一个最大项之外,没有额外的内存开销。如果您愿意,可以使用
''
连接元组。A very simple solution, likely similar to what is used by
more_itertools
, which takes advantage of the lexicographical order of permutations as suggested by @Brayoni, can be done by building an index of the iterable.Let's say you have
L = '1122'
. You can build a very simple index with something like this:Let's say you have a permutation
P
ofL
. It does not matter how many elementsP
has. Lexicographical ordering dictates that if you mapP
to using the index, it must always increase. MapP
like this:Now you can discard elements that are less than or equal to the maximum seen so far:
Notice that there is no additional memory overhead past keeping the last maximum item around. You can join the tuples with
''
if you like.