Search code examples
algorithmpowerset

Calculate Adjacent Powerset of an array


Internet is full of powerset algorithms.

But in my case, I need only powerset of adjacent parts.

Eg. From: [1, 2, 3], I'd need to get:

adjacentPowerset([1, 2, 3]) = [[1, 2, 3], [1, 2], [2, 3], [1], [2], [3]];
// Without [1, 3]

I'm struggling to achieve this...

A functional solution would be much appreciated (eventually recursive).


Solution

  • A non-empty range looks like xs[i:j] where i<j.

    You can use nested loops for this:

    def adj_powerset(xs):
        for i in xrange(len(xs)):
            for j in xrange(i, len(xs)):
                yield xs[i:j+1]
    
    print list(adj_powerset([1, 2, 3]))
    

    Output:

    [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]