4

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]
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
WlJs
  • 977
  • 1
  • 10
  • 12
  • What's your question? So far, you have only made a statement. Please update your question with information on what you tried already, where you got stuck and what you need to know to proceed. – blubb Sep 07 '11 at 13:33
  • This looks like hoemwork, please tag it accordingly. – Torsten Marek Sep 07 '11 at 13:37

2 Answers2

11
>>> 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']
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
1

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

Ofir
  • 8,194
  • 2
  • 29
  • 44