[英]generating all permutations of 2 ones and 3 zeroes with itertools
probably basic, but couldn't find it in any other question. 可能是基本的,但在其他任何问题中都找不到。 I tried:
我试过了:
print ["".join(seq) for seq in itertools.permutations("00011")]
but got lots of duplications, seems like itertools doesn't understand all zeroes and all ones are the same... 但是有很多重复,好像itertools不能理解所有的零,并且所有的都是一样的...
what am I missing? 我想念什么?
EDIT: 编辑:
oops. 哎呀。 Thanks to Gareth I've found out this question is a dup of: permutations with unique values .
多亏了Gareth,我才发现这个问题是一个重复的问题: 具有唯一值的排列 。 Not closing it as I think my phrasing of the question is clearer.
我认为我对这个问题的表述比较清楚,所以没有关闭它。
set("".join(seq) for seq in itertools.permutations("00011"))
list(itertools.combinations(range(5), 2))
returns a list of 10 positions where the two ones can be within the five-digits (others are zero): 返回十个位置的列表,其中两个可以在五位数之内(其他均为零):
[(0, 1),
(0, 2),
(0, 3),
(0, 4),
(1, 2),
(1, 3),
(1, 4),
(2, 3),
(2, 4),
(3, 4)]
For your case with 2 ones and 13 zeros, use this: 对于2个1和13个0的情况,请使用以下命令:
list(itertools.combinations(range(5), 2))
which returns a list of 105 positions. 返回105个职位的列表。 And it is much faster than your original solution.
而且它比原始解决方案快得多。
Now the function: 现在的功能:
def combiner(zeros=3, ones=2):
for indices in itertools.combinations(range(zeros+ones), ones):
item = ['0'] * (zeros+ones)
for index in indices:
item[index] = '1'
yield ''.join(item)
print list(combiner(3, 2))
['11000',
'01100',
'01010',
'01001',
'00101',
'00110',
'10001',
'10010',
'00011',
'10100']
and this needs 14.4µs. 这需要14.4µs。
list(combiner(13, 2))
returning 105 elements needs 134µs. 返回105个元素需要134µs。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.