0

The inputs for the function are

  1. a list of characters, eg: ['a','1']
  2. length of combinations

The function should output a list of all possible character combinations as a list.

For example, for input ['a','1'] and length of 2, the function should output:

[['a','a'],
['a','1'],
['1','a'],
['1','1']]

and if the length is 3, the output should be:

[['a','a','a'],
['a','a','1'],
['a','1','a'],
['a','1','1'],
['1','a','a'],
['1','a','1'],
['1','1','a'],
['1','1','1']]

1 Answer 1

1

You can use itertools.product with the repeat parameter:

from itertools import product

data = ['a', '1']
n = 3

print(list(list(p) for p in product(data, repeat=n)))

This gives an output of:

[['a', 'a', 'a'], ['a', 'a', '1'], ['a', '1', 'a'], ['a', '1', '1'], 
['1', 'a', 'a'], ['1', 'a', '1'], ['1', '1', 'a'], ['1', '1', '1']]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.