寻找更加pythonic的逻辑解决方案

man*_*007 6 python logic

我在Coding Bat做了一些练习问题,遇到了这个问题..

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 
Run Code Online (Sandbox Code Playgroud)

我的解决方案如下.

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
Run Code Online (Sandbox Code Playgroud)

有更多的pythonic方式吗?

Nik*_* B. 13

另一种适用于任意数量参数的可能性:

from collections import Counter

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

请注意,在Python 2中,您应该使用iteritems以避免构建临时列表.

  • @Daniel:Python 2.7应该是现在的标准,我通常认为它可用.如果`Counter`不可用,您可以使用`defaultdict(int)`轻松构建等效版本 (2认同)

Sve*_*ach 8

任何数量的参数的更通用的解决方案是

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)
Run Code Online (Sandbox Code Playgroud)


小智 8

怎么样:

def lone_sum(*args):
      return sum(v for v in args if args.count(v) == 1)
Run Code Online (Sandbox Code Playgroud)