Showing posts with label python data structures. Show all posts
Showing posts with label python data structures. Show all posts

Tuesday, March 27, 2018

Compare Sets


Compare Sets

We can check if a given set is a subset or superset of another set. The result is True or False depending on the elements present in the sets.

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
SubsetRes = DaysA <= DaysB
SupersetRes = DaysB >= DaysA
print(SubsetRes)
print(SupersetRes)

When the above code is executed, it produces the following result.

True
True



<<< Difference of Sets                      Go to Index               Nodes >>>




Difference of Sets


Difference of Sets

The difference operation on two sets produces a new set containing only the elements from the first set and none from the second set. In the below example the element “Wed” is present in both the sets so it will not be found in the result set.

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])

AllDays = DaysA – DaysB

print(AllDays)

When the above code is executed, it produces the following result. Please note the result has only one “wed”.

set(['Mon', 'Tue'])



<<< Intersection of Sets                              Go to Index                  Compare Sets >>>




Intersection of Sets


Intersection of Sets

The intersection operation on two sets produces a new set containing only the common elements from both the sets. In the below example the element “Wed” is present in both the sets.

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])

AllDays = DaysA & DaysB

print(AllDays)

When the above code is executed, it produces the following result. Please note the result has only one “wed”.

set(['Wed'])




<<< Union of Sets                      Go to Index                 Difference of Sets >>>




Union of Sets


Union of Sets

The union operation on two sets produces a new set containing all the distinct elements from both the sets. In the below example the element “Wed” is present in both the sets.

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])

AllDays = DaysA|DaysB

print(AllDays)

When the above code is executed, it produces the following result. Please note the result has only one “wed”.

set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])





<<< Remove Items                        Go to Index           Intersection of Sets >>>

Removing Item from a Set


Removing Item from a Set

We can remove elements from a set by using discard method. Again as discussed there is no specific index attached to the newly added element.

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])

Days.discard(“Sun”)
Print (Days)

When the above code is executed, it produces the following result.

set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])





<<< Adding Items                        Go to Index                   Union of Sets >>>