python中difference_Python sets: difference() vs symmetric_difference()

What is the difference between difference() and symmetric_difference() methods in python sets?

# Answer 1

4d350fd91e33782268f371d7edaa8a76.png

If a and b are sets

a - b

is everything in a that's not in b.

>>> a = {1,2,3}

>>> b = {1,4,5}

>>>

>>> a - b

{2, 3}

>>> b - a

{4, 5}

a.symmetric_difference(b) are all the elements that are in exactly one set, e.g. the union of a - b and b - a.

>>> a.symmetric_difference(b)

{2, 3, 4, 5}

>>> (a - b).union(b - a)

{2, 3, 4, 5}

# Answer 2

The difference between two sets (or groups of things) is not exactly the same as arithmetic difference.

GFSYK.png

Consider the two sets above (blue and green) as being two sets, or circles, that intersect each other. The yellow part being the intersection, what belongs to both sets.

Now consider what the set resulting from subtracting the greens from the blues should have. Should it have any greens? No. It will have blues that are not greens (or are not yellows, in the same logic). This is also true the other way around.

So you can get items from one set or the other, but not from both. I want to introduce to you, my little friend, symmetric difference. The gives you blues and greens, but not the yellows.

>>> a = {1,2,3}

>>> b = {1,4,5}

>>> a - b ## asymmetric difference

{2, 3}

>>> b - a ## asymmetric difference

{4, 5}

>>> a ^ b ## symmetric difference

{2, 3, 4, 5}

The asymmetric difference depends on what you do with a and b, or in what order you compare them. Look at it one way you get one thing, look a different way you get a different thing. Where the asymmetric difference, by definition, does not care which way you look at it.

Note. This is analogous behavior to that of a XOR. Hence the operator chosen in the python language. ^ is also used as a binary XOR if you give it numbers.

# Answer 3

The symmetric difference of two sets A and B is the set of elements

which are in either of the sets A or B but not in both.

However the difference of course, is self explanatory.

# Answer 4

This is how I have solved the Symmetric Difference problem on Hackerrank. Got full points for this :)

M = int(input())

sn = input()

sns = sn.split()

sns_list = set(map(int, sns))

N = int(input())

numbers = input()

separated_numbers = numbers.split()

separated_numbers_set = set(map(int, separated_numbers))

ans = list(sns_list.symmetric_difference(separated_numbers_set))

ans.sort()

for i in ans:

print(i)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值