1

I have been trying to understand senderle's answer to this question:- Cross product of sets using recursion

I find it simpler to work through for loops and then convert them to list comprehensions. I am struggling with this one as it has two list comprehensions in it, so I think we will need nested loops. sThe function returns a cartesian product of two lists.

def product(*seqs):
    if not seqs:
        return [[]]
    else:
        return [[x] + p for x in seqs[0] for p in product(*seqs[1:])]
# working example:        
x = [1, 2], [3, 4]
print(product(*x))
# gives: [[1, 3], [1, 4], [2, 3], [2, 4]]

How would I rewrite the product() function to expand out the list comprehension?

Andrew
  • 602
  • 7
  • 10

1 Answers1

3

You'd write the loops in the same order. The trick is to move the beginning [x] + p expression to the end. That's the part that changes order. You could convert the list comprehension to a generator:

for x in seqs[0]:
    for p in product(*seqs[1:]):
        yield [x] + p

That would change the return type of product(). If you want it to return lists and not generators, it'll look similar just with some extra bookkeeping.

l = []

for x in seqs[0]:
    for p in product(*seqs[1:]):
        l.append([x] + p)

return l
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • I would give you an extra +1 if I could for the help regarding returning lists and not generators. Thanks! – Andrew May 03 '16 at 14:36