Search code examples
cartesian-product

How to search for elements in the $n$-th power of a set without actually creating the $n$-th power set?


There is a given set S. I would like to search for elements from $S^n$ (the Cartesian product of $S$ with itself $n$ times) that verify certain properties. But I don't want to actually create $S^n$ because it takes up space.

For example to search for eligible elements in $S^3$, I could write

for x in S:
  for y in S:
    for z in S:
      if P(x,y,z): print (x,y,z)

However $n$ not being fixed when I write the code, I cannot use the above method. Is there a way to do this elegantly? (I use Python if that's relevant) Thanks!


Solution

  • You could write a function to generate the members of the desired power set:

    def powerset(s,n):
        if n==1:
            ys = [[]] 
        else:
            ys = powerset(s,n-1)
        for y in ys: 
            for x in s:
                yield [x]+y 
    
    >> list(powerset([1,2,3],3))
    
    [[1, 1, 1], [2, 1, 1], [3, 1, 1], [1, 2, 1], [2, 2, 1], [3, 2, 1], [1, 3, 1], [2, 3, 1], [3, 3, 1], [1, 1, 2], [2, 1, 2], [3, 1, 2], [1, 2, 2], [2, 2, 2], [3, 2, 2], [1, 3, 2], [2, 3, 2], [3, 3, 2], [1, 1, 3], [2, 1, 3], [3, 1, 3], [1, 2, 3], [2, 2, 3], [3, 2, 3], [1, 3, 3], [2, 3, 3], [3, 3, 3]]