Fun with One-liners
I have always enjoyed putting as much work as possible into a line, especially in higher level languages. In the crazy javascript (speaking of which, MochiKit 1.4 was finally release!) system I wrote (still need to put the final touches on that….), I was thrilled when I was able to combine all of the parts of my system into one one line. Since I mainly program in python, list comprehensions and generator expressions make it pretty easy to use one liners a lot, and at least with generators, it often means that is efficent too. Basically, what I am trying to say is that I love the one liner. Last night, while I was bored while doing my discrete homework, I came up with a memoized factorial function one liner. The standard, niave version is straightforward:
fac = lambda n: int(n==0) or n*fac(n-1)
Since I was bored, I wanted to see if I could memoize that expression, and still keep it in one line. Here is what I came up with:
fac_dict, fac = {}, lambda x: ((x in fac_dict or fac_dict.update({x:(lambda n: int(n==0) or fac(n-1)*n)(x)})) and False) or fac_dict[x]
which can be simplified slightly to:
fac_dict, fac = {0:1}, lambda x: ((x in fac_dict or fac_dict.update({x:(lambda n: fac(n-1)*n)(x)})) and False) or fac_dict[x]
There are still issues with recursion depth for large values, but a helper function could probably solve that.
I needed to write something for my blog, as I have gotten out of the habit, and this thing seemed as good as anything.
Posted in Python, coding, javascript | No Comments


