mankand007
mankand007

Reputation: 992

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?

Upvotes: 6

Views: 2023

Answers (7)

Ben J C
Ben J C

Reputation: 43

Had a very similar approach to what you had:

def lone_sum(a, b, c):

  if a != b and b != c and c != a:
    return a + b + c

  elif a == b == c:
    return 0 

  elif a == b:
    return c
  elif b == c:
    return a
  elif c == a:
    return b

Since if 2 values are the same the code will automatically return the remaining value.

Upvotes: 0

Bartolo Winz
Bartolo Winz

Reputation: 1

I tried this on Codingbat but it doesn`t work, although it does on the code editor.

def lone_sum(a, b, c): s = set([a,b,c]) return sum(s)

Upvotes: -1

kelvin
kelvin

Reputation: 65

def lone_sum(a, b, c):
    z = (a,b,c)
    x = []
    for item in z:
        if z.count(item)==1:
            x.append(item)
    return sum(x)

Upvotes: 0

Roger
Roger

Reputation: 116

How about:

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

Upvotes: 8

Niklas B.
Niklas B.

Reputation: 95278

Another possibility that works for an arbitrary number of arguments:

from collections import Counter

def lone_sum(*args):
    return sum(x for x, c in Counter(args).items() if c == 1)

Note that in Python 2, you should use iteritems to avoid building a temporary list.

Upvotes: 13

Agent Lenman
Agent Lenman

Reputation: 111

Could use a defaultdict to screen out any elements appearing more than once.

from collections import defaultdict

def lone_sum(*args):
  d = defaultdict(int)
  for x in args:
    d[x] += 1

  return sum( val for val, apps in d.iteritems() if apps == 1 )

Upvotes: 3

Sven Marnach
Sven Marnach

Reputation: 601361

A more general solution for any number of arguments is

def lone_sum(*args):
    seen = set()
    summands = set()
    for x in args:
        if x not in seen:
            summands.add(x)
            seen.add(x)
        else:
            summands.discard(x)
    return sum(summands)

Upvotes: 8

Related Questions