[Tutor] Better way to compare values?

Hugo Arts hugo.yoshi at gmail.com
Mon Aug 29 04:07:31 CEST 2011


On Mon, Aug 29, 2011 at 3:19 AM, memilanuk <memilanuk at gmail.com> wrote:
> Hello,
>
> Recently picked back up the Python bug, and have started chipping away at
> the warm-up exercises over @ codingbat.com.
>
> I'm getting thru the basic stuff okay, but I'm getting a feeling that maybe
> I'm not doing things the 'right' way, even though the results are correct.
>
> Specifically, checking if value 'a' OR value 'b' equal a certain number...
>
> The example that I'm on at the moment (like I said, starting over at the
> basics)...
>
> http://codingbat.com/prob/p124984
>
> My solution:
>
> '''
> Given 2 ints, a and b, return True if one if them is 10 or if their sum is
> 10.
>
> makes10(9, 10) = True
> makes10(9, 9) = False
> makes10(1, 9) = True
> '''
>
> def makes10(a, b):
>    if (a == 10) or (b == 10):
>        #print('Yep!')
>        return(True)
>
>    elif a + b == 10:
>        #print('Si!')
>        return(True)
>
>    else:
>        #print('Nein!')
>        return(False)
>
> makes10(10,9)
> #makes10(9,9)
> #makes10(1,9)
>
>
>
> In particular, the 'if (a == 10) or (b == 10): line... is there a
> shorter/more compact/more correct (i.e. pythonic) way of testing to see if a
> OR b is equal to 10?
>

There's a few things that can make this a lot shorter. To address your
primary question first, the python idiom for this is like so:

if 10 in (a, b):

it constructs a tuple containing the variables a and b, then checks if
the number ten is inside that tuple. simple and straightforward. Now,
or's aren't limited to just two operands. you can chain multiple or's
together to make this function even shorter, like so:

if a == 10 or b == 10 or a + b == 10:

That's pretty nice. And now, for the grand trick, we can apply out
little idiom we just learned up there to this three part if statement:

if 10 in (a, b, a + b):

See what we did there? But we can do you one better. this construction
I see a lot from beginning programmers:

def function(x):
    if x:
        return True
    else:
        return False

But it is actually quite superfluous. if you check if a certain
expression is true, and if so, return True, we may just as well return
the expression itself to begin with! We only need to make sure the
function returns only True or False, and we can do that nicely by
converting our initial expression to a boolean:

def function(x):
    return bool(x)

So, all said and done, the solution to your problem in idiomatic
python looks like this:

def makes10(a, b):
    return 10 in (a, b, a + b)

Note: I didn't have to use the bool() function in our last example,
because I know that the 'in' operator always returns either True or
False.

HTH,
Hugo


More information about the Tutor mailing list