NimueSTEM
NimueSTEM

Reputation: 303

Python use of itertools to find all combinations / permutations (with replacement)

I am sure this I am missing the point. Simple code:

from itertools import combinations_with_replacement

p1 = combinations_with_replacement("2357",3)
y = [''.join(i) for i in p1]
print (y)

Produces: ['222', '223', '225', '227', '233', '235', '237', '255', '257', '277', '333', '335', '337', '355', '357', '377', '555', '557', '577', '777']

I am looking to find all possible ways of pulling 3 from the 4 digits - where order matters. In my case, 755 is not returned as 557 has the same digits.

I am looking for: ['222','223','232' (new), '225', 252' (new) ] etc

Currently the use of combinations_with_replacement rejects sequences where the numbers have been previously drawn. I probably need "permutations" (but with replace) which seems to be missing.

What am I overlooking?

Cheers

Upvotes: 2

Views: 798

Answers (1)

user2390182
user2390182

Reputation: 73470

Use itertools.product since you seem to be looking for the entire cartesian product pool X pool X pool:

from itertools import product

p1 = product("2357", repeat=3)
y = [*map(''.join, p1)]
print(y)

Upvotes: 6

Related Questions