PEP 308: Obfuscated Nested Ternaries (INACAIS)

Bengt Richter bokr at oz.net
Sat Feb 22 14:41:20 EST 2003


On Thu, 20 Feb 2003 15:00:42 +0100, Gerrit Holl <gerrit at nl.linux.org> wrote:

>Hi,
>
>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)
>
>Actually, I would use case here if available:
>switch (x, y):
>    case (-1, -1): ...
>    case (-1, 0): ...
>    case (-1, 1): ...
>    case (0, -1): ...
>    case (0, 0): ...
>    case (0, 1): ...
>    case (-1, -1): ...
>    case (-1, 0): ...
>    case (-1, -1): ...
>
>I am using this to draw an arrow pointing to direction.
>The direction is given by (x, y) and the arrow should,
>obviously, point to that direction. INACAIS...
>
What about just indexing a list of tuples? E.g., (untested)

    result = [
       (br, tl, t, tl, l, tl), # -1,-1 -> 0,0 -> 0
       (r, l, t, l, b, l),     # -1,0 -> 0,1  -> 1
       (tr, bl, b, bl, l, bl), # -1,1 -> 0,2  -> 2
       (b, t, l, t, r, t),     # 0,-1 -> 1,0  -> 3
       (tl, tr, br, bl, tl),   # 0,0  -> 1,1  -> 4
       (t, b, l, b, r, b),     # 0,1  -> 1,2  -> 5
       (bl, tr, t, tr, r, tr), # 1,-1 -> 2,0  -> 6
       (l, r, t, r, b, r),     # 1,0  -> 2,1  -> 7
       (tl, br, b, br, r, br)  # 1,1  -> 2,2  -> 8
    ][(cmp(x,0)+1)*3+cmp(y,0)+1]

Regards,
Bengt Richter




More information about the Python-list mailing list