PEP 308: Obfuscated Nested Ternaries (INACAIS)

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Feb 21 03:49:39 EST 2003


Peter Hansen <peter at engcorp.com> wrote in 
news:3E54FC9C.98FF39A3 at engcorp.com:

>> def silly(x, y, t, l, b, r, tl, tr, bl, br):
>>     actions = {
>>         ( 1, 1): lambda: (tl, br,  b, br,  r, br),
>>         ( 1, 0): lambda: ( l,  r,  t,  r,  b,  r),
>>         ( 1,-1): lambda: (bl, tr,  t, tr,  r, tr),
>>         ( 0, 1): lambda: ( t,  b,  l,  b,  r,  b),
>>         ( 0, 0): lambda: (tl, tr, br, bl, tl),
>>         ( 0,-1): lambda: ( b,  t,  l,  t,  r,  t),
>>         (-1, 1): lambda: (tr, bl,  b, bl,  l, bl),
>>         (-1, 0): lambda: ( r,  l,  t,  l,  b,  l),
>>         (-1,-1): lambda: (br, tl,  t, tl,  l, tl)
>>         }
>> 
>>     seq = actions[cmp(x,0), cmp(y,0)]()
>>     return seq
> 
> Why is the lambda required?  Aren't you just retrieving
> a tuple?
For this particular situation it probably doesn't make any difference, but 
in the general case the difference is that only the one tuple is evaluated, 
whereas without the lambda we evaluate every branch every time.

If I hadn't used the lambda someone would probably have complained that my 
answer didn't have exactly the same semantics as the original.

Another advantage to my solution is that it is immediately obvious that one 
branch yields a tuple of a different length than the others. This probably 
indicates a bug, and although I'm sure it would have shown up in the unit 
tests, there's no harm in making it visible in the code.
> 
> (But your point is excellent.  Didn't the timbot once generate
> something words about every problem in Python being solvable 
> with dicts?)

Dicts are a great tools to solve problems, but they aren't the only tool. 
We all fall into the trap of applying a solution just because its the one 
we know well.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list