In this example, we have defined two set variables and we have performed different set operations: union, intersection, difference and symmetric difference.
To understand this example, you should have the knowledge of the following Python programming topics:
Python offers a datatype called set whose elements must be unique. It can be used to perform different set operations like union, intersection, difference and symmetric difference.
Source Code
# Program to perform different set operations like in mathematics
# define three sets
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};
# set union
print("Union of E and N is",E | N)
# set intersection
print("Intersection of E and N is",E & N)
# set difference
print("Difference of E and N is",E - N)
# set symmetric difference
print("Symmetric difference of E and N is",E ^ N)
Output
Union of E and N is {0, 1, 2, 3, 4, 5, 6, 8}
Intersection of E and N is {2, 4}
Difference of E and N is {8, 0, 6}
Symmetric difference of E and N is {0, 1, 3, 5, 6, 8}
In this program, we take two different sets and perform different set operations on them. This can equivalently done by using set methods.
Related posts:
Python Program to Make a Simple Calculator
Python Program to Get the Last Element of the List
Java Program to Implement the Program Used in grep/egrep/fgrep
Python Global, Local and Nonlocal variables
Debug a JavaMail Program
Python Program to Display the multiplication Table
Python String startswith()
Python Dictionary get()
Python Dictionary items()
Python oct()
Python range()
Python Program to Solve Quadratic Equation
Python String isspace()
Python String title()
Python String split()
Python List insert()
Python Program to Count the Number of Occurrence of a Character in String
Python Program to Find Factorial of Number Using Recursion
Python Program to Check if a Number is Odd or Even
Python slice()
Python Program to Find All File with .txt Extension Present Inside a Directory
Deep Learning with Python - Francois Chollet
Python List Comprehension
Python Program to Get Line Count of a File
Python String index()
Python Program to Split a List Into Evenly Sized Chunks
Python Functions
Python List index()
Python Program to Create a Countdown Timer
Python Get Current time
Python eval()
Python Program to Sort a Dictionary by Value