π

17.10 Set Operations

Set Operations

Python can perform union, difference, symmetric difference, intersection on sets.
``````x = {1, 2, 3, 4, 5}
y = {3, 4, 5, 6, 7}
print(x.intersection(y))  # prints {3, 4, 5}
print(x.difference(y))  # prints {1, 2}
print(x.symmetric_difference(y))  # prints {1, 2, 6, 7}
print(x.union(y))  # prints {1, 2, 3, 4, 5, 6, 7}

# here's some other ways to express set operations
print(x-y)  # same thing as difference
print(x&y)  # same thing as intersection``````
View on GitHub
The methods with `_update` in the name do the same thing as the named operation, except it automatically assigns the returned value to the set the method was called from. In other words, the `_update` methods mutate the original set instead of returning a new set.
``````x = {'p', 'y', 't', 'h', 'o', 'n'}
y = {'c', 'o', 'd', 'i', 'n', 'g'}
x.intersection_update(y)
print(x)  # prints {'o', 'n'}``````

Practice

Open Mind

Two brothers come together to watch TV every day. On weekdays (monday through thursday), they are not open-minded and only watch what they like to watch themselves. Due to this, it is possible for nothing to be watched. On weekends (friday through sunday), they are open-minded and would watch what they themselves like to watch and what the others like to watch even if they themselves donβt like to watch that specific TV show.
Assume, all the TV shows the brothers like will be played every day. Given a day (1-4 represents weekday and 5-7 represents weekend) and two sets (what the brothers each like to watch), return the set of possible TV shows the brothers would both watch on that day.
π» Template code

Β
βοΈ