Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Cartesian Product [duplicate]

Tags:

python

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
like image 316
Dustin Avatar asked Feb 01 '12 18:02

Dustin


1 Answers

I'd use itertools.product():

for l in itertools.product(*letters):
    print ''.join(l)
like image 157
NPE Avatar answered Oct 17 '22 07:10

NPE