Saturday, December 11, 2004

python maddness

I recently send around a bug I found (in my own code!) to some of my collegues as a puzzle and hid the answer in the end in the following obfuscatedpython bit:
"You will get the answer when you execute this from command-line:

python -c "import new, sys;print (lambda s: s and s[-1]+new.function(sys._getframe().f_code, globals())(s[:-1]) or s)('.srotarepo noisrevnoc fo eraweB :nosseL \n.tcejbo TNOFH gniylrednu eht llik lliw rotcurtsed s\'tnoFC lanigiro eht dna ,ton si tI \n.tcerroc yllacitnames si tnemngissa tnoFC taht kniht uoy sekam rotcurtsnoc gnitpecca-TNOFH eht htiw noitanibmoc ni rotarepo noisrevnoc TNOFH\n')"

The only really cool (and hopefully useless :) thing here is the list/string reverse function written as a recursive lambda. Of course there is no normal way to call a lambda in python recursively since it doesn't have a name, so you have to poke around the current frame object to get what you want. So you get this beauty:

(lambda s: s and s[-1]+new.function(sys._getframe().f_code, globals())(s[:-1]) or s)

I think I'll go take a shower now :)

0 Comments:

Post a Comment

<< Home