BokBok - 1 year ago 68

Python Question

I found this one line function on the python wiki that creates a set of all sets that can be created from a list passed as an argument.

`f = lambda x: [[y for j, y in enumerate(set(x)) if (i >> j) & 1] for i in range(2**len(set(x)))]`

Can someone please explain how this function works?

Answer Source

To construct the powerset, iterating over `2**len(set(x))`

gives you all the binary combinations of the set.

```
range(2**len(set(x))) == [00000, 00001, 00010, ..., 11110, 11111]
```

Now you just need to test if the bit is set in `i`

to see if you need to include it in the set, e.g.:

```
>>> i = 0b10010
>>> [y for j, y in enumerate(range(5)) if (i >> j) & 1]
[1, 4]
```

This would be equivalent to:

```
[[y for j, y in enumerate(set(x)) if i[j]] for i in itertools.product([0,1], repeat=len(set(x))+1)]
```