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

What is the output of this puzzle?


# cancer-fighting foods
cf = {"basil",

# blood pressure reducing foods
bf = {"bananas",
      "red beets",

print(len(cf & bf))


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.

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!

Related Video




Leave a Comment