I'm just a computer scientist who happens to have a tumblr. I'm specially interested in artificial intelligence and research, atually I'm a PhD student, so the posts will probably be related with these circumstances.
jmora
September 6, 2009
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.

  1. def lattice(l):
  2. for i in range(2**len(l)):
  3. 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:

  1. 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.

Comments
blog comments powered by Disqus