Stupid ways to spell simple code
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun Jun 30 13:36:54 EDT 2013
On Sun, 30 Jun 2013 16:06:35 +1000, Chris Angelico wrote:
> So, here's a challenge: Come up with something really simple, and write
> an insanely complicated - yet perfectly valid - way to achieve the same
> thing. Bonus points for horribly abusing Python's clean syntax in the
> process.
Here's a trivially stupid way to find the length of an iterable:
sum(1 for obj in iterable)
(except it isn't actually stupid, if the iterable is an iterator, and you
don't mind consuming it to find out home many items it had). This leads
to an obvious obfuscation:
sum(('.' for obj in iterable), '').count('.')
but sadly Python, in a rare case of protecting you from shooting your own
foot off, doesn't allow this. Never mind, we can defeat the safety catch
on sum() and complicate the code at the same time:
sum(('.' for obj in iterable), type('S', (),
{'__add__': lambda self, o: o})()).count('.')
Obfuscated *and* quadratic performance. Do I win?
Wait, I can beat that. Sorting is too trivial in Python:
alist.sort()
Pfft! Where's the challenge in that? Let's use an O(n!) algorithm for
sorting -- yes, n factorial -- AND abuse a generator expression for its
side effect. As a bonus, we use itertools, and just for the lulz, I
obfuscate as many of the names as I can:
from random import shuffle as OOO00O
from itertools import takewhile as OO0O0O, count as O0OO0O
OO0O00 = range(5)
list(OO0O0O(lambda O: any(O[O0] < O[O0-1] for O0 in
range(1, sum(('O' for O in O), type('O', (),
{'__add__': lambda O0O, OO0: OO0})()).count('O'))),
(OOO00O(OO0O00) or OO0O00 for O in O0OO0O())))[0]
--
Steven
More information about the Python-list
mailing list