Post

The Botanical Garden and Rose Garden: Understanding Sets

The Botanical Garden and Rose Garden: Understanding Sets

{% raw %}

Introduction to the Botanical Garden

We are planning to opening a botanical garden with flowers which will attract people to visit.

Morning: Planting Unique Flowers

One morning, we decides to plant flowers in the garden. They ensure that each flower they plant is unique.

botanical_garden = {"Rose", "Lily", "Sunflower"}

Noon: Adding More Flowers

At noon, they find some more flowers and add them to the garden, making sure they only add flowers that aren’t already there.

Adding Elements to a Set:

# Adding more unique flowers to the enchanted gardenbotanical_garden.add("Jasmine")botanical_garden.add("Hibiscus")print(botanical_garden)# output: {'Hibiscus', 'Rose', 'Tulip', 'Sunflower', 'Jasmine'}

Afternoon: Trying to Plant Duplicate Flowers

In the afternoon, they accidentally try to plant another Rose, but the garden’s rule prevents any duplicates from being added.

Adding Duplicate Elements:

# Attempting to add a duplicate flowerbotanical_garden.add("Rose")print(botanical_garden)# output: {'Lily', 'Sunflower', 'Rose'}

Evening: Removing Unwanted Plants

As evening approaches, they decide to remove some flowers they no longer want in their garden.

Removing Elements from a Set:

# Removing a flower from the enchanted gardenbotanical_garden.remove("Lily")print(botanical_garden)# output: {'Sunflower', 'Rose'}

Night: Checking Flower Types

Before going to bed, they check if certain flowers are present in their botanical garden.

Checking Membership:

# Checking if certain flowers are in the gardenis_rose_in_garden = "Rose" in botanical_gardenis_tulip_in_garden = "Tulip" in botanical_gardenprint(f"Is Rose in the garden? {is_rose_in_garden}")print(f"Is Tulip in the garden? {is_tulip_in_garden}")# Output# Is Rose in the garden? True# Is Tulip in the garden? False

Midnight: Comparing with Rose Garden

Late at night, they compare their botanical garden with their rose garden to see which flowers they have in common and which are unique to each garden.

Set Operations:

Intersections:

# Neighbor's enchanted gardenrose_garden = {"Rose", "Lavender"}# Flowers in both gardens (Intersection)common_flowers = botanical_garden.intersection(rose_garden)print(f"Common flowers: {common_flowers}")# Output# Common flowers: {'Rose'}# Unique flowers: {'Sunflower'}# All unique flowers: {'Sunflower', 'Lavender', 'Rose'}

Difference:

# Flowers unique to their garden (Difference)unique_flowers = botanical_garden.difference(rose_garden)print(f"Unique flowers: {unique_flowers}")#output# Unique flowers: {'Sunflower'}

Union:

# All unique flowers from both gardens (Union)all_unique_flowers = botanical_garden.union(rose_garden)print(f"All unique flowers: {all_unique_flowers}")# Output: All unique flowers: {'Sunflower', 'Lavender', 'Rose'}

{% endraw %}

This post is licensed under CC BY 4.0 by the author.