5

Possible Duplicate:
Get the cartesian product of a series of lists in Python

I'm trying to figure out some logic that I just can't wrap my head around. Say I have the following data structure:

letters = (
    ('b','c'),
    ('a','e','ee'),
    ('d','f'),
    ('e','y'),
)

How would I iterate through this to get every possible string combination:

bade
cade
bede
cede
beede
ceede
bafe
cafe
befe
cefe
beefe
ceefe
bady
cady
bedy
cedy
beedy
ceedy
bafy
cafy
befy
cefy
beefy
ceefy
Community
  • 1
  • 1
Dustin
  • 3,965
  • 5
  • 27
  • 33
  • 4
    You are looking for the cartesian product: http://docs.python.org/library/itertools.html#itertools.product – Felix Kling Feb 01 '12 at 18:22
  • @Dustin, I don't think what you want is the cartesian product, but the combinations of those strings. Keep in mind that the cartesian product is an operation between two sets `A` and `B` in which `AxB = {(a, b): a ∈ A and b ∈ B}` – lmiguelvargasf Apr 03 '19 at 00:19

1 Answers1

6

I'd use itertools.product():

for l in itertools.product(*letters):
    print ''.join(l)
NPE
  • 486,780
  • 108
  • 951
  • 1,012