- [Instructor] On line one, two, three,
we have defined three sets,
group one, group two, group three.
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 group one and group two
and also in group three?
Let us 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 group one,
if color in group two
and color in group three,
then what we can do is common elements dot add, color.
Our color must be common between all the three sets.
Color is already present in group one.
Then we checked if the color is present in group two,
and then you can check if the color is present
in group three.
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,
group one, group two, group three, are.
Colors that are present in all the groups,
group one, group two, group three are,
and then we can print common colors.
Now let us run the program
and see what is the output.
Python 3,
space intersection.py.
And now you can see colors
that are present in all the groups,
group one, group two, group three 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 an 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 dot intersection.
Intersection is the built-in method.
And here we can write
group one intersection, group two, group three.
Print common elements between
group one, group two, group three are,
and then we can print the result.
Python 3 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 group one and group two and group three.
Print common element present between the groups are,
and then we can print the output.
And the operator is used to find intersection,
Python 3 intersection.py.
You can see and compare the result returned
by each of the three method.
The result is same.