1

I would like to produce all combinations of certain length by using a set of allowed characters with replacement:

I thought itertools.combinations_with_replacement is what I need. So this is what I did:

from itertools import combinations_with_replacement
allowed = ['0', '1', '8', '6', '9']
comb = list(combinations_with_replacement(allowed,2))

Yet the number of combinations thus produced is 15. But it should be 25 (5^2). What is going on?

EDIT:

I replaced combinations_with_replacement with permutations as suggested by @Michael Bianconi but it did not work either - I get a result set of 20, not 25.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Nick
  • 2,924
  • 4
  • 36
  • 43

2 Answers2

3
00, 01, 08, 06, 09
11, 18, 16, 19
88, 86, 89
66, 69
99

There are 15 possible combinations.

Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
2

You probably search for the product:

import itertools
allowed = ['0', '1', '8', '6', '9']
product = list(itertools.product(allowed, repeat=2))
print(len(product))

25

Strings are iterable in Python, so you can use:

import itertools
for result in itertools.product('01869', repeat=2)):
    print(result)
Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64