# Daily Python Puzzle: How to Intersect two Sets in Python?

#### What is the output of this puzzle?

[python]
# cancer-fighting foods
cf = {“basil”,
“berries”,
“broccoli”,
“curcume”,
“garlic”,
“kale”,
“oranges”,
“seeds”,
“spinach”,
“sprouts”}

# blood pressure reducing foods
bf = {“bananas”,
“berries”,
“fish”,
“garlic”,
“kale”,
“red beets”,
“salmon”,
“seeds”,
“spinach”,
“yogurt”}

print(len(cf & bf))
[/python]

This puzzle is about two pieces of basic knowledge.

The first piece of basic knowledge is what your mother always told you is true: vegetables and fruits are healthy. Eat 5 portions of vegetables and fruits per day or more and you will live longer.

The second piece of basic knowledge is as profane as how to create and manipulate sets in Python. You need sets for all sorts of algorithms and code snippets to maintain data.

A set is an unordered collection of elements. Each element can exist at most once in a set. We say that there are no duplicate elements.

Studying Python sets in detail will make you a better coder. Period. Read this tutorial on Python sets to learn more!

The one big advantage of sets over lists is that checking whether an element is in the set (containment operation) is much faster. No matter how large the set is, containment requires only constant time. In contrast, the containment operation for lists requires checking each list element. This becomes very slow for large lists.

In this puzzle, we want to know how many foods are both cancer-fighting and blood pressure reducing. This can be done with set intersection. Intersecting two sets A and B creates a new set with all elements that are contained in both sets A and B.
We can either use the `intersection()` function or the ‘&’ operator to intersect two Python sets. In the puzzle are five foods that fight caner and reduce blood pressure: berries, garlic, spinach, kale, and seeds.

Are you a master coder?
Test your skills now!

5