Looking for a more pythonic logical solution

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.


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)

How about:

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

Tags:

Python

Logic