3

This prints nothing:

from itertools import combinations
comb = combinations([1,2], 3)
for i in comb:
    print(i)

I want output as :

(1,2,2) (1,2,1) (1,1,2) (1,1,1) (2,1,2) (2,1,1) (2,2,1) (2,2,2)
krunal kp
  • 81
  • 6
  • 1
    The reason that using the functions called `combinations` or `permutations` don't give you what you want, and searches for those terms don't get you answers, is that *the things you want are not called combinations*. This is really more of a math terminology question than a programming question. – Karl Knechtel Aug 28 '20 at 06:14

2 Answers2

6

Seems like you just want the product, not combinations:

from itertools import product

for i in product([1, 2], repeat=3):
    print(i)

combinations is getting you unique combinations without reusing elements within any combination, which means pulling three elements from two source elements is impossible. It's also order-insensitive, so it wouldn't give you (1, 2) and (2, 1) even if you only asked for combinations of size 2 (only permutations would do that). In your case, you seem to want to cycle every element through every index, allowing repeats (which combinations/permutations won't do) and order-sensitive (which combinations_with_replacement won't do), which leaves product.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

You can't generate 3 element combinations from a 2 item list. Try this:

comb = combinations([1,2]*3, 3)

This basically extends the iterable to a 6-item list ([1, 2, 1, 2, 1, 2]).

Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • 1
    This produces a lot of duplicate outputs (20 total, vs. the OP's desired eight unique outputs). – ShadowRanger Aug 28 '20 at 05:59
  • Wow this works , the problem is only repetition. But is there any reason that you multiply list [1,2] by **3** and not by anything else ? @Selcuk – krunal kp Aug 28 '20 at 06:00