Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combinations or permutations of input, for a given length

I have been trying to calculate all the permutations for two characters (E and L) as it happens, for a given sequence length. If I import itertools and run itertools.permutation('LE', 8) I get no output, obviously if i only pass itertools.permutation('LE') I will get the permutations that are two long ie LE and EL. Is there a way of running the permutations in such a way that I would have the arguments 'LE' and a number, say 3 which would then result in:

LLL
EEE
LLE
EEL
LEE
ELL
ELE
LEL

Thanks in advance.

like image 373
user2178117 Avatar asked Dec 04 '25 15:12

user2178117


1 Answers

What you want is a cartesian product LE × LE × LE.

Use itertools.product with the repeat argument:

In [60]: list(itertools.product('LE', repeat=3))
Out[60]:
[('L', 'L', 'L'),
 ('L', 'L', 'E'),
 ('L', 'E', 'L'),
 ('L', 'E', 'E'),
 ('E', 'L', 'L'),
 ('E', 'L', 'E'),
 ('E', 'E', 'L'),
 ('E', 'E', 'E')]

 

In [62]: [''.join(p) for p in itertools.product('LE', repeat=3)]
Out[62]: ['LLL', 'LLE', 'LEL', 'LEE', 'ELL', 'ELE', 'EEL', 'EEE']
like image 63
Pavel Anossov Avatar answered Dec 07 '25 05:12

Pavel Anossov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!