awkward101
awkward101

Reputation: 87

Is there a better, shorter code for this?

I'm trying to learn python and one of the sites that I'm working with has one of the problem as follows: Given two int values, a and b, return True if either one is 6. Or if their sum or difference is 6.

and here's my code for it

def love6(a, b):
  diff = a-b
  sum = a+b
  if a==6 or b==6:
    return True
  elif sum==6 or abs(diff)==6:
    return True
  else:
    return False

This is fine and works perfect - just wondering if this could be compressed further?

Upvotes: 0

Views: 128

Answers (2)

PM 2Ring
PM 2Ring

Reputation: 55469

Why waste time pre-computing the sum & absolute difference when they may not be needed?

def love6(a, b): 
    return a==6 or b==6 or a+b==6 or abs(a-b)==6

The Python or operator short-circuits, so the above tests are evaluated left to right, and once a True value is found, no more tests are performed. Eg, if a or b equal 6, then the sum isn't calculated, and the absolute difference is only calculated if neither a nor b equal 6, and their sum isn't 6.

Upvotes: 6

lvc
lvc

Reputation: 35059

Since two branches of your if do the same thing, you can merge them into one by linking them with another or:

if a==6 or b==6 or sum==6 or abs(diff)==6:
    return True
else:
    return False

but this is just:

return (a == 6 or b == 6 or sum==6 or abs(diff)==6)

But since all of them are testing the same equality, you can use the in operator like so:

return 6 in (a,b,sum,abs(diff))

It's worth avoiding the variable name sum, since there's a builtin function with that name. Here, you're only using it once and the operation is quite simple, so you can drop the variables completely without any appreciable loss in clarity:

return 6 in (a,b,a+b,abs(a-b))

Upvotes: 7

Related Questions