0

Hi All,

I wanna generate all possible combination of certain list using python.

For Example I have a list like

list = ['A','B','C']

I wanna generate all possible combination of these list elements like using "itertools":

AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
BAA
BAB
BAC
BBA
BBB
BBC
BCA
BCB
BCC
CAA
CAB
CAC
CBA
CBB
CBC
CCA
CCB
CCC

Thanks!

6
Contributors
7
Replies
12
Views
5 Years
Discussion Span
Last Post by pyTony
0

Here is a way using my snippet on non recursive tree traversal 1.4

from functools import partial
import walktree as wt

def subn(letters, k, node):
    if len(node) == k:
        return
    for x in letters:
        yield node + x

for path in wt.walk("", partial(subn, "ABC", 3), wt.event(wt.leaf)):
    print path[-1]

"""my output -->
AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
BAA
BAB
BAC
BBA
BBB
BBC
BCA
BCB
BCC
CAA
CAB
CAC
CBA
CBB
CBC
CCA
CCB
CCC
"""
0

Technically you want a selection **which allows sequence items to be repeated,
a **combination
or permutation does not:

def selections(seq, n):
    """
    selections(seq, n) is a recursive generator where
    seq is an iterable object
    n is the sample size
    n = len(seq) is the max sample size
    returns a list of lists of unique sample size items
    """
    if n == 0:
        yield []
    else:
        for i in range(len(seq)):
            # recursion
            for ss in selections(seq, n - 1):
                yield [seq[i]] + ss


# use 'ABC' or ['A', 'B', 'C']
iterable = 'ABC'
sample_size = len(iterable)
sel = list(selections(iterable, sample_size))

# show as strings
for item in sel:
    s = "".join(item)
    print(s)

""" my result >>>
AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
BAA
BAB
BAC
BBA
BBB
BBC
BCA
BCB
BCC
CAA
CAB
CAC
CBA
CBB
CBC
CCA
CCB
CCC
"""
1

itertools.product will also do this.

import itertools
import pprint

letters = ['A', 'B', 'C']
pprint.pprint(list(itertools.product(letters, repeat=3)))

"""Output-->
[('A', 'A', 'A'),
 ('A', 'A', 'B'),
 ('A', 'A', 'C'),
 ('A', 'B', 'A'),
 ('A', 'B', 'B'),
 ('A', 'B', 'C'),
 ('A', 'C', 'A'),
 ('A', 'C', 'B'),
 ('A', 'C', 'C'),
 ('B', 'A', 'A'),
 ('B', 'A', 'B'),
 ('B', 'A', 'C'),
 ('B', 'B', 'A'),
 ('B', 'B', 'B'),
 ('B', 'B', 'C'),
 ('B', 'C', 'A'),
 ('B', 'C', 'B'),
 ('B', 'C', 'C'),
 ('C', 'A', 'A'),
 ('C', 'A', 'B'),
 ('C', 'A', 'C'),
 ('C', 'B', 'A'),
 ('C', 'B', 'B'),
 ('C', 'B', 'C'),
 ('C', 'C', 'A'),
 ('C', 'C', 'B'),
 ('C', 'C', 'C')]
 """

Edited by snippsat

1

As you gave ready answers, let's spell out this obvious answer (this is abandoned thread anyway, OP visitted last 2 days ago):

letters = list('ABC')
for a in letters:
    for b in letters:
        for c in letters:
            print(a+b+c)

Other point is that these are not combinations but permutations with repeat.

Edited by pyTony

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.