Finding a more logical pythonic solution

I was doing some practice problems in Bat coding and came across this ...

Given 3 int values, abc, 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 as follows.

 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 to do this?

+6
source share
4 answers

What about:

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

Another feature 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 must use iteritems to avoid creating a temporary list.

+13
source

More general solution for any number of arguments

 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) 
+8
source

You can use the defaultdict parameter to display any items that appear 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 ) 
+2
source

Source: https://habr.com/ru/post/917009/


All Articles