Skip to content

Commit 7a8f03e

Browse files
author
Harshita Singla
committed
Union and intersection of two arrays
1 parent 260e3d8 commit 7a8f03e

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
'''
2+
A list that has the common distinct element from both arrays and
3+
if there are repetitions of the element then only one occurrence
4+
is considered, known as the union of both arrays.
5+
6+
A list that has common distinct elements from both arrays,
7+
is the intersection of both arrays.
8+
9+
10+
Example:
11+
Input: a[] = {1, 2, 2, 3, 4, 8, 10}, b[] = {4, 6, 3, 1}
12+
Output: {1, 2, 3, 4, 6, 8, 10}
13+
Explanation: 1, 2, 3, 4, 6, 8 and 10 is the union of
14+
elements present in array a[] and array b[].
15+
16+
Input: a[] = {1, 2, 2, 3, 4, 8, 10}, b[] = {4, 6, 3, 1}
17+
Output: {1, 2, 3, 4}
18+
Explanation: 1, 2, 3, and 4 are the intersection(common elements)
19+
of elements present in array a[] and array b[].
20+
21+
22+
'''
23+
24+
#Taking input lists from user
25+
26+
a=list(map(int,input('Enter elements of first list:').split()))
27+
b=list(map(int,input('Enter elements of second list:').split()))
28+
# Example Input
29+
#Enter elements of first list: 3 4 6 4 4 6 7 41
30+
#Enter elements of second list: 78 3 5 7 -1 9 2 -5
31+
32+
33+
34+
'''bitwise or (|) between the sets of both arrays
35+
to find union and assign it into a variable A
36+
in the form of lists.
37+
bitwise and (&) between the sets of both arrays
38+
to find intersection and assign it into a variable A
39+
in the form of lists.
40+
'''
41+
42+
43+
A=list(set(a)|set(b))
44+
B=list(set(a)&set(b))
45+
46+
47+
48+
print('Union of the arrays:',A)
49+
print('intersection of the arrays:',B)
50+
51+
#Output
52+
'''Union of the arrays: [2, 3, 4, 5, 6, 7, 41, 9, 78, -5, -1]
53+
intersection of the arrays: [3, 7]
54+
'''

0 commit comments

Comments
 (0)