Non-overlapping sum of two sets in Python

In this tutorial, we will learn how to find the non-overlapping sum of two sets in Python.

Problem Statement

We are given two sets, we have to find the sum of all elements which are not common in them.

In a set, the value of the element identifies it and is always unique.

 

Examples

  • Input:    Set1 = {1 , 2 , 4 , 7}                Set2 = {2 , 7 , 5 , 9}

Output:  19   (4 + 1 + 5 + 9)

  • Input:    Set1={1 , 3 , 5 , 6 }                 Set2={ }

Output:  15   (1 + 3 + 5 + 6)               //as Set2 is empty all elements of Set1 will be added

  • Input:    Set1={1 , 2 , 3 , 4}                 Set2={4 , 1 , 3 , 2}

Output:  0                                       //order does not matter in sets –both the sets are equal

 

Method 1- Naive Approach non-overlapping sum of two sets

For every element in Set1 check whether it exists in Set2 or not. For checking if an element exists in the set or not we traverse through the entire set. If it does not exist in Set2 add it to the sum.

Similarly, traverse through all the elements of Set2 and check whether it exists in Set1 or not (by traversing through the entire Set1 each time).

 

Set1 = {1 , 3 , 6 , 7 , 9}
Set2 = {7 , 5 , 1 , 4 , 2}   #7, 1 are common in Set1 and Set2

ans=0

for x in Set1:     #traversing through every element of Set1
    a=0
    for y in Set2:  #checking if the element exists in Set2 or not
        if x==y:    #if it exists in Set2, we will not add it
            a=1
            break
    if a==0:
        ans+=x


for x in Set2:     #repeating this procedure for all emements of Set2
    a=0
    for y in Set1:
        if x==y:
            a=1
            break
    if a==0:
        ans+=x

print(ans)

Output

29

 

Method 2 – Non-overlapping sum of two sets in Python

In this code instead of traversing through the entire set, to check if an element exists in the set or not, we will use the inbuilt function not in.

NOT IN: Returns True if the specified value is not present in the object

 

Set1 = {1 , 3 , 6 , 7 , 9}
Set2 = {7 , 5 , 1 , 4 , 2} #7, 1 are common in Set1 and Set2

ans=0
 
for x in Set1:          #checking for all elements of Set1
    if x not in Set2:   # if element does not exist in Set2 add it
        ans+=x


for y in Set2:          #checking for all elements of Set2
    if y not in Set1:
        ans+=y

print(ans)

Output

29

 

Method 3- Using symmetric_difference() Method

Set1.symmetric_differnce(Set2): Returns a set that contains all items from both sets (x and y), except items that are present in both sets.

 

Set1 = {1 , 3 , 6 , 7 , 9}
Set2 = {7 , 5 , 1 , 4 , 2} #7, 1 are common in Set1 and Set2

Set3=Set1.symmetric_difference(Set2)
#creates a set which contains all elements of Set1 and Set2 except those which are common to both of them

ans=0

for x in Set3:
    ans+=x

print(ans)

Output

29

 

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *