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?