-1

I have a list of n letters as strings such as:

input: ["A", "B", "C", "D"]

What I need to do is create all possible combinations of these letters with given length, for example if:

L = 2
output: ["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"], ["C", "D"]

L = 3
output: ["A", "B", "C"], ["A", "B", "D"], ["A", "C", "D"], ["B", "C", "D"]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    What have you tried, and what exactly is the problem with it? You've tagged [tag:itertools] and [tag:combinations], so did you look into either of those? – jonrsharpe Apr 21 '21 at 16:04

3 Answers3

-1

This is your standard combinations which is available in itertools:

import itertools

characters = "ABCD"
print(list(itertools.combinations(characters, 2)))
print(list(itertools.combinations(characters, 3)))

You'll find other useful functions for iterating inside itertools such as permutations.

nuric
  • 11,027
  • 3
  • 27
  • 42
-1

You can simply use itertools and permutations. You pass it your list of characters and the length of the permutation.

import itertools

my_list = ["A", "B", "C", "D"]
print(list(itertools.permutations(my_list, 2)))
# [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'A'), ('B', 'C'), ('B', 'D'), ('C', 'A'), ('C', 'B'), ('C', 'D'), ('D', 'A'), ('D', 'B'), ('D', 'C')]
print(list(itertools.permutations(my_list, 3)))
#[('A', 'B', 'C'), ('A', 'B', 'D'), ('A', 'C', 'B'), ('A', 'C', 'D'), ('A', 'D', 'B'), ('A', 'D', 'C'), ('B', 'A', 'C'), ('B', 'A', 'D'), ('B', 'C', 'A'), ('B', 'C', 'D'), ('B', 'D', 'A'), ('B', 'D', 'C'), ('C', 'A', 'B'), ('C', 'A', 'D'), ('C', 'B', 'A'), ('C', 'B', 'D'), ('C', 'D', 'A'), ('C', 'D', 'B'), ('D', 'A', 'B'), ('D', 'A', 'C'), ('D', 'B', 'A'), ('D', 'B', 'C'), ('D', 'C', 'A'), ('D', 'C', 'B')]
Johnny John Boy
  • 3,009
  • 5
  • 26
  • 50
-2

You can use itertools.permutations to get permutations of a specified length.

from itertools import permutations 

print(list(permutations(my_list, L)))
Mady Daby
  • 1,271
  • 6
  • 18