Search code examples
pythonlogic

Looking for a more pythonic logical solution


I was doing some practice problems in Coding Bat, and came across this one..

Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum. 

lone_sum(1, 2, 3) → 6
lone_sum(3, 2, 3) → 2
lone_sum(3, 3, 3) → 0 

My solution was the following.

def lone_sum(a, b, c):
   sum = a+b+c
   if a == b:
     if a == c:
         sum -= 3 * a
     else:
         sum -= 2 * a
   elif b == c:
     sum -= 2 * b
   elif a == c:
     sum -= 2 * a
   return sum

Is there a more pythonic way of doing this?


Solution

  • How about:

    def lone_sum(*args):
          return sum(v for v in args if args.count(v) == 1)