A lattice from a list in python
Sometimes I astonish myself after writing a piece of code, usually when it is compact and efficient, so usually these are small pieces of code, yet I still remember the spreadsheet application I made in haskell. This is the latest piece of code with which I’ve surprised myself.
- def lattice(l):
- for i in range(2**len(l)):
- yield [l[j] for j in range(len(l)) if (2**j & i) != 0]
And of course there is also a functional-comprehension-list lover version:
- lattice = lambda l: [[l[j] for j in range(len(l)) if (2**j & i) != 0] for i in range(2**len(l))]
For a given list it calculates all the possible combinations of its elements, this is the whole lattice composed with them. I’ve not compared the efficiency empirically, but avoiding the generation of duplicates to remove them later, recursion and other characteristics that are common in any straightforward implementation should mean something.