简体   繁体   English

在Python中生成满足某些约束的所有列表

[英]Generating all lists that satisfy certain constraints in Python

I would like to generate the following lists in Python: 我想在Python中生成以下列表:

[1, 1, 1, 2, 2]
[1, 1, 2, 1, 2]

... etc

[2, 1, 2, 1, 1]
[2, 2, 1, 1, 1]

There are always two "2"s and three "1"s in any list. 任何列表中始终有两个“ 2”和三个“ 1”。

My intuition suggests that I will need to use the itertools module to do this. 我的直觉表明,我将需要使用itertools模块来执行此操作。 However, I am not sure where to begin, though I have read the documentation and looked at examples. 但是,尽管我已经阅读了文档并查看了示例,但是我不确定从哪里开始。 Any suggestions? 有什么建议么?

You can notice that the number of such lists is equal to the number of ways to place two "2"s in a sequence of length 5. This suggests the following solution: 您会注意到,这样的列表的数量等于在长度为5的序列中放置两个“ 2”的方式的数量。这建议以下解决方案:

n = 5 # total length
n2 = 2 # number of "2"s
for idx in itertools.combinations( xrange(n), n2 ):
    print [ 2 if i in idx else 1 for i in xrange(n) ]

It's easy to see that the answer using permutations is iterating over n! 很容易看到,使用排列的答案在n!上迭代n! solutions, while my solution iterates over n!/( (n-n2)! * n2!) . 解决方案,而我的解决方案遍历n!/( (n-n2)! * n2!) For example if the input list is [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2] , the solution using permutations is ~90,000,000 times slower (10! * 4!) 例如,如果输入列表为[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2] 1,1,1,1,1,1,1,1,1,1,2,2,2,2 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2] ,则使用置换的解决方案要慢90,000,000倍(10!* 4!)

You can use itertools.permutations and set (to eliminate duplicates): 您可以使用itertools.permutations并进行set (以消除重复项):

>>> from itertools import permutations
>>> for combo in set(permutations([1, 1, 1, 2, 2])):
...     print(list(combo))
...
[1, 2, 1, 1, 2]
[2, 1, 1, 1, 2]
[2, 1, 2, 1, 1]
[2, 1, 1, 2, 1]
[1, 1, 2, 1, 2]
[1, 1, 1, 2, 2]
[1, 2, 1, 2, 1]
[1, 1, 2, 2, 1]
[1, 2, 2, 1, 1]
[2, 2, 1, 1, 1]
>>>

If the combinations need to be in order, then you can use sorted : 如果需要按顺序排列组合,则可以使用sorted

>>> for combo in sorted(set(permutations([1, 1, 1, 2, 2]))):
...    print(list(combo))
...
[1, 1, 1, 2, 2]
[1, 1, 2, 1, 2]
[1, 1, 2, 2, 1]
[1, 2, 1, 1, 2]
[1, 2, 1, 2, 1]
[1, 2, 2, 1, 1]
[2, 1, 1, 1, 2]
[2, 1, 1, 2, 1]
[2, 1, 2, 1, 1]
[2, 2, 1, 1, 1]
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM