Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 581
WlJs Avatar asked Sep 08 '25 16:09

WlJs


2 Answers

>>> 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']
like image 101
Tim Pietzcker Avatar answered Sep 10 '25 07:09

Tim Pietzcker


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).

like image 34
Ofir Avatar answered Sep 10 '25 06:09

Ofir