python combination with replacement not working as expected
Question:
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.
Answers:
00, 01, 08, 06, 09
11, 18, 16, 19
88, 86, 89
66, 69
99
There are 15 possible combinations.
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)
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.
00, 01, 08, 06, 09
11, 18, 16, 19
88, 86, 89
66, 69
99
There are 15 possible combinations.
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)