- [Instructor] On line one, two, three,
we have defined three sets:
group1, group2, group3.
Each set has LEGO blocks in it
and these are the colors of those LEGO blocks.
Now, how would you find out LEGO block color
that is present in group1 and group2
and also in group3?
Let use see how we can solve the problem
without using any built-in method.
What we can do is common_elements is equal to.
We can initialize this with a set.
And then we can iterate over one of the sets.
So for color in group1,
if color in group2
and color in group3,
then what we can do is common_elements.add color.
A color must be common between all the three sets.
Color is already present in group1,
then we check if the color is present in group2
and then you can check if the color
is present in group3.
If the color is present,
it will get added to the common_elements set.
Instead of common_elements,
we can write common_colors.
And here also we can write common_colors.
And now we can print.
Color that is present in all the groups,
group1, group2, group3 are.
Colors that are present
in all the groups, group1, group2, group3 are,
and then we can print common_colors.
Now let us run the program
and see what is the output.
Python3
space intersection.py.
And now you can see colors that are present
in all the groups, group1, group2, group3
is an empty set.
Now, why is this an empty set?
You can verify the result
by manually checking if there is any color
that is common between all the sets.
As we can see, there is no element
that is common between all the sets.
That's why the result is am empty set.
Now how the same problem can be solved
without using loops.
To find common elements between the sets,
there is a built-in method named as intersection.
Following is the Venn diagram for intersection.
The diagram shows that the method returns common elements
that are present between the sets.
We can solve the same problem
in fewer steps just by doing result
is equal to common_colors.intersection.
Intersection is the built-in method.
And here we can write group1.intersection,
group2, group3.
Print Common elements between group1, group2, group3 are
and then we can print the result.
Python3 intersection.py
and again, the result is an empty set.
This is so because there are no common elements
between the sets that we have.
Another way to do the same thing
is by using operators.
So group1 and group2 and group3.
Print Common element present between the groups are
and then we can print the output.
And operator is used to find intersection.
Python3 intersection.py.
You can see and compare the result returned by each
of the three methods.
The result is same.