oreid
oreid

Reputation: 1507

How do I generate a list of permutations based on given characters and a length?

For example,

I have a list of characters that I want to generate permutations of e.g. ['*', '+'] and a length that I want the permutations to be generated off e.g. 2. In other words, I want to find all the combinations of the supplied list up to the supplied length. A call to generatePermutations might look like this.

generatePermutations(['*', '+'], 2)

Which should return:

*, *
*, +
+, *
+, +

Another example would be:

generatePermutations(['*', '+'], 3)
*, *, *
*, *, +
*, +, +
*, +, *
+, *, +
+, *, *
+, +, *
+, +, +

How would I go about doing this?

Upvotes: 0

Views: 81

Answers (1)

Paul Rooney
Paul Rooney

Reputation: 21609

Use itertool.product. What you are asking for is the cartesian product.

Examples

>>> list(itertools.product(['*', '+'], repeat=2))
[('*', '*'), ('*', '+'), ('+', '*'), ('+', '+')]
>>> list(itertools.product(['*', '+'], repeat=3))
[('*', '*', '*'), ('*', '*', '+'), ('*', '+', '*'), ('*', '+', '+'), ('+', '*', '*'), ('+', '*', '+'), ('+', '+', '*'), ('+', '+', '+')]

Upvotes: 2

Related Questions