开发者

Variations with repetition [duplicate]

开发者 https://www.devze.com 2023-04-03 10:47 出处:网络
This question already has answers here: How to get the Cartesian product of multiple lists (18 answers)
This question already has answers here: How to get the Cartesian product of multiple lists (18 answers) Closed 5 months ago.

Given a list of e.g. two elements l = [1,0] I need to create 开发者_开发技巧all possible 5-element variations with repetitions. I've tried itertools.combinations but give me what I wanted.

With given n = 2 and k = 5 I should get 2^5 = 32 elements and the result should look like this:

results = [11111,11110,11101,11100,11001,11011,11010,...00000]


>>> import itertools
>>> ["".join(item) for item in itertools.product("10", repeat=5)]
['11111', '11110', '11101', '11100', '11011', '11010', '11001', '11000', '10111', 
'10110', '10101', '10100', '10011', '10010', '10001', '10000', '01111', '01110', 
'01101', '01100', '01011', '01010', '01001', '01000', '00111', '00110', '00101', 
'00100', '00011', '00010', '00001', '00000']


This is equivalent to looping over 0..k^n-1 and outputting the current index in base n. Which reduces your problem to base conversion (which is essentially equivalent to long division).

0

精彩评论

暂无评论...
验证码 换一张
取 消