# PEP 308: Obfuscated Nested Ternaries (INACAIS)

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Feb 20 15:22:56 CET 2003

```Gerrit Holl <gerrit at nl.linux.org> wrote in
news:mailman.1045749596.2787.python-list at python.org:

> For the Obfuscated Contest: rewrite this peace of code
> using ternaries. Preferably with a lot of ('s and )'s :)
>
>     if x > 0:
>         if y > 0:
>             seq = (tl, br, b, br, r, br)
>         elif y == 0:
>             seq = (l, r, t, r, b, r)
>         else:
>             seq = (bl, tr, t, tr, r, tr)
>     elif x == 0:
>         if y > 0:
>             seq = (t, b, l, b, r, b)
>         elif y == 0:
>             seq = (tl, tr, br, bl, tl)
>         else:
>             seq = (b, t, l, t, r, t)
>     else:
>         if y > 0:
>             seq = (tr, bl, b, bl, l, bl)
>         elif y == 0:
>             seq = (r, l, t, l, b, l)
>         else:
>             seq = (br, tl, t, tl, l, tl)
>

Who needs ternaries?

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

--
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?

```