Personal tools
You are here: Home News Some Cunning Python
Log in


Forgot your password?
New user?
Advertisement
 

Some Cunning Python

by admin last modified Mar 21, 2009 08:29 PM
— filed under:

As you have almost certainly noticed by now if you are watching (and according to Google Analytics, no one is :)), the Neo-Capitalism Wiki is very slowly gaining content. As soon as I am freed from this albatross which is university study, I am very much looking forward to finally getting some of what is in my head into the wiki - for now, I grab an hour or two when I can in between the pointless labour of gaining yet more unnecessary bits of academic qualification.

Something of interest: in the process of hacking the DTML in ZWiki to show the children of the pages as well as their ancestors, I had need to deflatten a list i.e. to convert ['a', 'b', 'c', 'd'] into ['a', ['b', ['c', ['d']]]] and worse still, I needed to do it as an inline function because of how DTML works (ok, I could define a DTML function I know, but that sounded like hassle when there was an opportunity for some truly nasty Python scripting!). What I have come up with is truly appalling: a recursive lambda function:

Python 2.4.5 (#2, Aug  1 2008, 02:20:59)
[GCC 4.3.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x=['a', 'b', 'c', 'd']
>>> print (lambda f, a: f(f, a))(lambda x, y: (lambda:[y[0], x(x, y[1:])], lambda:y)[1==len(y)](), x)
['a', ['b', ['c', ['d']]]]
>>>

Horrible eh! I have used lambda's to implement both recursive lambda's and a ternary operator - nevertheless, it works, though passing it much of a long list would quickly exhaust the stack due to the use of a double trampoline.

Document Actions
Add comment

You can add a comment by filling out the form below. Plain text formatting.

(Required)
Tell us your name.
(Required)
Enter your e-mail address.
(Required)
(Required)
(Required)
Please complete the reading test or listening test below in order to prove your humanity.