Python重复的非重复int [英] Python sum of non duplicate int
本文介绍了Python重复的非重复int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我给了3个int,a,b,c。如果它们是唯一的,我想找到所有三个int的总和。如果a,b或c具有与任何其他值相同的值,则它们不计入总和。
I am given 3 int, a, b, c. I would like to find the sum of all three int provided that they are unique. If a, b, or c has the same values as any of the other values, then they don't count towards the sum.
示例1:
a = 3, b = 3, c =3
sum = 0
示例2
a = 1, b = 3, c =3
sum = 1
这就是我所做的。如果没有那么多if else语句,是否有更多的pythonic方法呢?
This is what I have done. Is there a more pythonic way of doing this without so many if else statements?
def lone_sum(a, b, c):
if a != b and b != c and a != c:
return a + b + c
elif a == b == c:
return 0
elif a == b:
return c
elif b == c:
return a
elif a == c:
return b
推荐答案
from collections import Counter
def lone_sum(a, b, c):
d = Counter([a, b, c])
return sum(k for k in d if d[k]==1)
添加任意数量的数字:
Add any number of numbers:
def lone_sum(*L):
d = Counter(L)
return sum(k for k in d if d[k]==1)
添加完全重复的数字 c
次:
Add numbers repeated exactly c
times:
def rep_sum(c, *L):
d = Counter(L)
return sum(k for k in d if d[k]==c)
添加最多重复的数字 c
次:
Add numbers repeated at most c
times:
def rep_sum(c, *L):
d = Counter(L)
return sum(k for k in d if d[k]<=c)
...或者如果你感到无聊并想要真正有创意:
... or if you're bored and want to get really creative:
def lone_sum(*L):
nums = set()
all_nums = set()
for num in L:
if num in nums:
nums.remove(num)
elif num not in all_nums:
all_nums.add(num)
nums.add(num)
return sum(nums)
这篇关于Python重复的非重复int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文