(a==b) ? 'Yes' : 'No'

Steve Howell showell30 at yahoo.com
Fri Apr 2 10:26:19 EDT 2010


On Apr 2, 7:05 am, Steve Howell <showel... at yahoo.com> wrote:
> On Apr 2, 2:04 am, Steven D'Aprano <st... at REMOVE-THIS-
>
>
>
> cybersource.com.au> wrote:
> > On Thu, 01 Apr 2010 21:16:18 -0700, Steve Howell wrote:
> > > The ironic thing about the ternary operator is that it is not really
> > > ternary; it's binary.  Even just making an expression from a binary
> > > operator inevitably leads to syntax hell.
>
> > > There is a principle of programming that I would like to coin, which is
> > > the "Tyranny of Three."
>
> > > It is impossible to code for any expression that has three possible
> > > values in any kind of elegant way.  It's just impossible.  Try to code
> > > the bowling game without tearing out your teeth--three conditions:
> > > strike, spare, or normal.
>
> > > The tyranny of three is that 3 is too small for an elegant N-based
> > > solution and too large for a simple condition.
>
> > I'm afraid I don't understand any of that. Can you explain further?
>
> > How is the ternary operator "not really ternary, it's binary"? It
> > requires three arguments, not two, which makes it ternary. In Python
> > syntax:
>
> Of course, I understand that the ternary operator has three arguments,
> but it only has two possible outcomes.
>
> You asked me to elaborate on the "Tyranny of Three."  Let's say you
> have three possible outcomes.
>
> In some languages you would write something like this:
>
> mark = (rolls == 1) && (pins == 10) ? 'strike' :
>        (rolls == 2) && (pins == 10) ? 'spare' :
>                                       'normal'
>
> Many people consider the above very ugly, so they write it like so:
>
>   if pins == 10:
>      if rolls == 1:
>         return 'strike'
>      else:
>         return 'spare'
>   else:
>      return 'normal'
>
> Then the next programmer comes along and "cleans up":
>
>   if pins == 10:
>     return 'strike' if rolls == 1 else 'spare'
>   else:
>     return 'normal'
>
> Then there is this alternative:
>
>   if rolls == 2:
>     return 'spare' if pins == 10 else 'normal'
>   else:
>     return 'strike'
>
> And then:
>
>   if rolls == 2:
>     if pins == 10
>       return 'spare'
>     else
>       return 'normal
>   else:
>     return 'strike'
>
> Or even this:
>
>    return 'strike' if rolls == 1 else ('spare' if pins == 10 else
> 'normal')
>
> The "Tyranny of Three" refers to a problem where there are an infinite
> number of valid solutions, but none of them have any essential beauty,
> so they lead to endless nitpicking and code churn.

I forgot this one:

def obfuscated_triager(rolls, pins,
        lookup = ['normal'] * 10 + ['strike'] + [None] * 9 + ['spare']
        ):
    return lookup[rolls * pins]




More information about the Python-list mailing list