To find union and intersection of two arrays in python; This tutorial will show you how to find union and intersection of two arrays in python.
Both union and intersection are different things. You can read below the both of them.
Union:- A list that has the common distinct element from both arrays and if there are repetitions of the element then only one occurrence is considered, known as the union of both arrays.
Intersection:- A list that has common distinct elements from both arrays, is the intersection of both arrays.
Python Program Find Union and Intersection of Two Arrays
- Algorithm to find union and intersection of two arrays
- Python program to find union and intersection of two arrays
Algorithm to find union and intersection of two arrays
- First of all, Take two lists from the user.
- Take the bitwise or (|) between the sets of both arrays to find union and assign it into a variable X in the form of lists.
- To find the intersection of between two arrays, use the bitwise and (&) between the sets of given arrays and assign it into a variable Y in the form of lists.
- Print variable X and Y which is our required output.
Python program to find union and intersection of two arrays
Use the following steps to write a python program to find union and intersection of two arrays:
- Take input Two arrays from the user in the program.
- Find the union and intersection of these arrays bitwise operators.
- Store result in different variables.
- Print result.
# Program to find the union and intersection of two arrays #take input two array from user firstArr=list(map(int,input('Enter elements of first list:').split())) secondArr=list(map(int,input('Enter elements of second list:').split())) # find the union and intersection of two arrays #using bitwise operators x=list(set(firstArr)|set(secondArr)) y=list(set(firstArr)&set(secondArr)) #print list print('Union of the arrays:',x) print('intersection of the arrays:',y)
After executing the program, the output will be:
Enter elements of first list: 2 5 6 Enter elements of second list: 5 7 9 6 Union of the arrays: [2, 5, 6, 7, 9] intersection of the arrays: [5, 6]