Variations with repetition [duplicate]
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).
精彩评论