28

I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

  1. Dictionary hack:

    name = {a and b and c: 'first',
            a and b and not c: 'second',
            a and not b and c: 'third',
            a and not b and not c: 'fourth',
            not a and b and c: 'fifth',
            not a and b and not c: 'sixth',
            not a and not b and c: 'seventh',
            not a and not b and not c: 'eighth'}[True]
    

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

  1. And/or magic

    name = (a and b and c and 'first' or
            a and b and not c and 'second' or
            a and not b and c and 'third' or
            a and not b and not c and 'fourth' or
            not a and b and c and 'fifth' or
            not a and b and not c and 'sixth' or
            not a and not b and c and 'seventh' or
            not a and not b and not c and 'eighth')
    

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

4
  • 2
    Another drawback of #2: It fail when one of the values to be mapped to is falsy (e.g. 0).
    – user395760
    Commented Jan 18, 2011 at 17:24
  • 2
    +1 for a practical code golf :)
    – user50049
    Commented Jan 20, 2011 at 16:12
  • 1
    it seems some have read 'first', 'second' as arbitrary placeholders, while other read them as the actual strings you need to produce. I'm curious - could you please shed light on this? Commented Jan 22, 2011 at 19:11
  • They are placeholders indicating a general case.
    – exupero
    Commented Jan 28, 2011 at 20:34

11 Answers 11

50

You can think of a, b, and c as three bits that when put together form a number between 0 and 7. Then, you can have an array of the values ['first', 'second', ... 'eighth'] and use the bit value as an offset into the array. This would just be two lines of code (one to assemble the bits into a value from 0-7, and one to lookup the value in the array).

Here's the code:

nth = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
nth[(a and 4 or 0) | (b and 2 or 0) | (c and 1 or 0)]
9
  • +1 exactly what I was thinking: stackoverflow.com/questions/4726949/… :P But It took me a while to know how to write the ternary operator in python. I used something like this for this FizzBuzz solution in Java : rosettacode.org/wiki/FizzBuzz#Using_an_array :)
    – OscarRyz
    Commented Jan 18, 2011 at 17:40
  • 3
    Couldn't you drop the or 0 parts? Commented Jan 18, 2011 at 17:40
  • Sven, probably so. My Python is a bit rusty. :-) Commented Jan 18, 2011 at 17:42
  • 4
    @Sven it is, and yes, that's possible: nth[(a and 4)|( b and 2)|(c and 1)] works well.
    – OscarRyz
    Commented Jan 18, 2011 at 17:46
  • 2
    I believe cleaner version of (a and 4 or 0) is (4 if a else 0). It looks more obvious. Correct me if I am wrong.
    – Tadeck
    Commented Mar 1, 2012 at 23:07
30

How about using a dict?

name = {(True, True, True): "first", (True, True, False): "second",
        (True, False, True): "third", (True, False, False): "fourth",
        (False, True, True): "fifth", (False, True, False): "sixth",
        (False, False, True): "seventh", (False, False, False): "eighth"}

print name[a,b,c] # prints "fifth" if a==False, b==True, c==True etc.
14
  • 1
    +1 exactly what I did when confronted with something very similar. With a comment # first boolean means x, second means y, third means z of course. (You got the lookup syntax wrong in the last line, should be print name[(a,b,c)] or print name[a,b,c]).
    – user395760
    Commented Jan 18, 2011 at 17:21
  • 1
    @delnan: Thanks, I noticed that, too - and I hadn't thought about dropping the parens around the tuple. Nice that it works without them. Tuple packing/unpacking, huh? Commented Jan 18, 2011 at 17:27
  • No, it's not tuple unpacking. Tuples don't need parentheses, except some ambiguity arises by omitting them. Commented Jan 18, 2011 at 17:30
  • 12
    +1 Simple is better than complex. Encoding the bits as a int may seem clever, but in the end it's just a unnecessary additional step. Commented Jan 18, 2011 at 17:58
  • 2
    @OzcarRyz if it grows, I'd consider binary to generate keys when building the table, but leave the lookup structure as is. It's really the natural data structure for this. Commented Jan 18, 2011 at 19:23
11

Maybe not much better, but how about

results = ['first', 'second', 'third', 'fourth', 
           'fifth', 'sixth', 'seventh', 'eighth']
name = results[((not a) << 2) + ((not b) << 1) + (not c)]
9
  • @SilentGhost: I always get confused with operator precedence -- added the missing parens :) Commented Jan 18, 2011 at 17:28
  • Very obfuscated code imo. I know why it works, but it's too clever. (Edit @Sven: It used to have a problem, as SilentGhost noted)
    – user395760
    Commented Jan 18, 2011 at 17:30
  • 2
    Not my downvote, but it's hard to read and highly magick. I'd definitely recommend against this if anyone else is ever supposed to read the code. Commented Jan 18, 2011 at 17:33
  • @Lennart: I would also recommend against using this as a general pattern, but I actually never came across something like this in real code :) Commented Jan 18, 2011 at 17:37
  • 2
    Strange, this reads fine to me. I think it is clever, but not overly clever or dangerous sorcery. +1.
    – user50049
    Commented Jan 20, 2011 at 16:11
5

if a,b,c are really booleans:

li = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
name = li[a*4 + b*2 + c]

if they are not booleans:

li = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
a,b,c = map(bool,(a,b,c))
name = li[a*4 + b*2 + c]

idea from Clint Miller

2

Since your getting all the combinations, you could create an index based on the values like this:

def value(a,b,c ): 
   values = ['8th','7th','6th','5th','4th','3rd','2nd','1st']
   index = ( 4 if a else 0 ) + ( 2 if b else 0 ) + ( 1 if c else 0 )
   return values[index]

if __name__ == "__main__":
   print value(True,  True,  True )
   print value(True,  True,  False )
   print value(True,  False, True )
   print value(True,  False, False )
   print value(False, True,  True )
   print value(False, True,  False)
   print value(False, False, True )
   print value(False, False, False)

output:

1st
2nd
3rd
4th
5th
6th
7th
8th
1

What about nested ifs - it means you don't have to check everything several times and reads clearer to me (although maybe not quite as clever as some of the other answers):

if a:
    if b:
        if c:
            name="first"
        else:
            name="second"
    else:
        if c:
            name="third"
        else:
            name="fourth"
else:
    if b:
        if c:
            name="fifth"
        else:
            name="sixth"
    else:
        if c:
            name="seventh"
        else:
            name="eighth"
2
  • 1
    +1: not clever, but the most readable. at least you understand what's going on without scratching your head. Commented Jan 18, 2011 at 20:02
  • I'm not downvoting, but I think it's horrible. I think clint's solution plus a good comment is the best Commented Jan 18, 2011 at 21:35
1

Another option would be to create a helper function:

def first_true(*args):
    true_vals = (arg for arg in args if arg[0])
    return next(true_vals)[1]

name = first_true((a and b and c, 'first'),
                  (a and b and not c, 'second'),
                  (a and not b and c, 'third'),
                  (a and not b and not c, 'fourth'),
                  (not a and b and c, 'fifth'),
                  (not a and b and not c, 'sixth'),
                  (not a and not b and c, 'seventh'),
                  (not a and not b and not c, 'eighth'))

This method assumes that one of the tests passed in will be true. It could also be made lazier with lambdas.

1
  • My apologies, late night, no excuse but still. Commented Mar 2, 2012 at 0:14
1

To measure speeds:

from time import clock
a,b,c = True,False,False

A,B,C,D,E,F,G,H = [],[],[],[],[],[],[],[]


for j in xrange(30):


    te = clock()
    for i in xrange(10000):
        name = (a and b and c and 'first' or
                a and b and not c and 'second' or
                a and not b and c and 'third' or
                a and not b and not c and 'fourth' or
                not a and b and c and 'fifth' or
                not a and b and not c and 'sixth' or
                not a and not b and c and 'seventh' or
                not a and not b and not c and 'eighth')
    A.append(clock()-te)



    te = clock()
    for i in xrange(10000):
        if a and b and c:
            name = 'first'
        elif a and b and not c:
            name = 'second'
        elif a and not b and c:
            name = 'third'
        elif a and not b and not c:
            name = 'fourth'
        elif not a and b and c:
            name = 'fifth'
        elif not a and b and not c:
            name = 'sixth'
        elif not a and not b and c:
            name = 'seventh'
        elif not a and not b and not c:
            name = 'eighth'
    B.append(clock()-te)

    #=====================================================================================

    li = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = li[a*4 + b*2 + c]
    C.append(clock()-te)

    #=====================================================================================

    nth = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = nth[(a and 4 or 0) | (b and 2 or 0) | (c and 1 or 0)]
    D.append(clock()-te)


    nth = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = nth[(a and 4 or 0) + (b and 2 or 0) + (c and 1 or 0)]
    E.append(clock()-te)

    #=====================================================================================

    values = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = values[( 4 if a else 0 )| ( 2 if b else 0 ) | ( 1 if c else 0 )]
    F.append(clock()-te)


    values = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = values[( 4 if a else 0 ) + ( 2 if b else 0 ) + ( 1 if c else 0 )]
    G.append(clock()-te)

    #=====================================================================================

    dic = {(True, True, True): "first",
           (True, True, False): "second",
           (True, False, True): "third",
           (True, False, False): "fourth",
           (False, True, True): "fifth",
           (False, True, False): "sixth",
           (False, False, True): "seventh",
           (False, False, False): "eighth"}
    te = clock()
    for i in xrange(10000):
        name = dic[a,b,c]
    H.append(clock()-te)




print min(A),'\n', min(B),'\n\n', min(C),'\n\n', min(D),'\n',min(E),'\n\n',min(F),'\n', min(G),'\n\n', min(H)

Result

0.0480533140385 
0.0450973517584 

0.0309056039245 

0.0295291720037 
0.0286550385594 

0.0280122194301 
0.0266760160858 

0.0249769174574
1
  • If the object creation happens as often as the query (such as: both once) and is included in the measure, then the second option (the ifs) is by far the fastest. Commented Jan 22, 2011 at 1:26
0

I'd go for the list/bits solution of @OscarRyz, @Clint and @Sven, but here's another one:


S1 = frozenset(['first', 'second', 'third', 'fourth'])
S2 = frozenset(['first', 'second', 'fifth', 'sixth'])
S3 = frozenset(['first', 'third', 'fifth', 'seventh'])
last = 'eighth'
empty = frozenset([])

def value(a, b, c): for r in (a and S1 or empty) & (b and S2 or empty) & (c and S3 or empty): return r return last

2
  • did you actually test anything to say that dictionary is the least efficient? I have and on my machine tim's solution is much faster than either sven's or clint's. Commented Jan 18, 2011 at 18:05
  • No, it was just a mere estimation. I think you're right and tim's solution being faster. I probably had in mind the other "dictionary solution" when i wrote that. Thanks for pointing it out, I'll edit my answer.
    – primroot
    Commented Jan 18, 2011 at 18:57
0

if your goal is to avoid writing a lot of "ands" and boolean expressions you can use prime number and only one conditions like this (example for 2 conditions)

 cond = (2**cond_1)*(3**cond_2)

so

cond == 1 #means cond_1 and cond_2 are False
cond == 2 #means cond_1 is True and con_2 is False
cond == 3 #means cond_1 is False and con_2 is True
cond == 6 #means con_1 and Con_2 are True

This hack can be used for 3 conditions using 3 primes and so on

Like this...

cond = (2**a)*(3**b)*(5**c)
name = {30:'first', 6: 'second', 10:'third', 2:'fourth',
        15:'fifth', 3:'sixth', 5:'seventh', 1:'eighth'}[cond]
0
-1

Here is a truth table approach:

lookup = {'000': 'eighth',
          '001': 'seventh',
          '010': 'sixth',
          '011': 'fifth',
          '100': 'fourth',
          '101': 'third',
          '110': 'second',
          '111': 'first'}

def key(a, b, c):
    return ''.join([str(a),str(b),str(c)])

name = lookup[key(0,1,1)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.