Skip to content

Latest commit

 

History

History
461 lines (340 loc) · 12.7 KB

08.Set.md

File metadata and controls

461 lines (340 loc) · 12.7 KB

Lesson 8: Data Structures p.3 (set)

Sets are the guardians of uniqueness, ensuring each element stands out. Be like a set, stand out from the crowd!"

Content

  1. Introduction to Sets
  2. Methods of sets
  3. Set Comprehensions
  4. frozenset() Overview
  5. Quiz
  6. Homework

1. Introduction to Sets

A set - is a mutable, unordered collection of items in Python.

Every element is unique (no duplicates). and must be immutable (cannot be changed).

1.1 Syntax

Sets can be created using curly braces {} or the set() function. However, an empty set can only be created using the set() function, using {} as it creates an empty dictionary.

Example

my_set = {1, 2, 3}      
print(my_set)
print("Type is:", type(my_set))

empty_set = set()
print(empty_set)
print("Type of empty set is:", type(empty_set))

dictionary = {}         # Be careful it is NOT a ``set``
print(dictionary)
print("Type is:", type(dictionary))

Output

{1, 2, 3}
Type is: <class 'set'>
set()
Type of empty set is: <class 'set'>
{}
Type is: <class 'dict'>

1.2 Convert iterables into sets

Converting other iterables to sets can be useful for several reasons:

  • Eliminating Duplicates: Sets automatically remove duplicate elements, which is useful for getting unique items.
  • Efficient Membership Testing: Checking whether an item exists in a set is faster compared to lists or tuples.

As for me, it is very underestimated data sctructure among py devs' community, because based on my current experience I haven't seen many solutions where sets were used in production code.

The syntax for converting an iterable to a set involves the set() constructor.

Example

# Converting a list to a set
my_list = [1, 2, 3, 2, 1]
my_set = set(my_list)
print(my_set)

# Converting a tuple to a set
my_tuple = (4, 5, 6, 5, 4)
my_set = set(my_tuple)
print(my_set)

# Converting a string to a set
my_string = "hello"
my_set = set(my_string)
print(my_set)

Output

{1, 2, 3}
{4, 5, 6}
{'e', 'h', 'l', 'o'}

Bear in mind that the order of elements in sets can be different from time to time you output the elements.

1.3 Indexing and Slicing

Sets do NOT support indexing or slicing.

This sounds logically, as there is no order in how elements are stored and they can't be accessed by index.

Example

my_set = {1, 2, 3}

# The following lines will raise an error
print(my_set[0])
print(my_set[0:2])

Output

TypeError: 'set' object is not subscriptable

1.4 Math operations and built_in functions.

You can do various math operations with sets in Python.

Python's built-in functions like len(), max(), min(), sum(), and sorted() can also be applied to sets.

Alt text

Example

# Define two sets
A = {1, 2, 3}
B = {3, 4, 5}

# Perform set operations
union = A | B  # or A.union(B)
intersection = A & B  # or A.intersection(B)
difference = A - B  # or A.difference(B)
symmetric_difference = A ^ B  # or A.symmetric_difference(B)

# Display the results
print("Union:", union)
print("Intersection:", intersection)
print("Difference:", difference)
print("Symmetric Difference:", symmetric_difference)

# Apply built-in functions
length = len(A)
max_value = max(A)
min_value = min(A)
sum_value = sum(A)
sorted_list = sorted(A)  # Note: sorted() returns a list

# Display the results
print("Length:", length)
print("Max:", max_value)
print("Min:", min_value)
print("Sum:", sum_value)
print("Sorted:", sorted_list)

# Membership test
print("-" * 10)
print(1 in A)
print("A" in A)

Output

Union: {1, 2, 3, 4, 5}
Intersection: {3}
Difference: {1, 2}
Symmetric Difference: {1, 2, 4, 5}
Length: 3
Max: 3
Min: 1
Sum: 6
Sorted: [1, 2, 3]
----------
True
False

1.5 Set Comparisons

Set comparison operators in Python enable you to compare sets based on their contents, allowing you to check for subset, superset, or equality relationships. These operations are particularly useful when dealing with collections of elements where the focus is on the presence or absence of items rather than their order or frequency.

1.5.1 Subset and Superset

  • A subset (<) is a set where all its elements are contained within another set.
  • A superset (>) is a set that contains all elements of another set.

Python provides the <, <=, >, and >= operators, along with the methods .issubset(), .issuperset() for these comparisons.

1.5.2 Equality

  • Two sets are considered equal (==) if they contain the same elements, regardless of their order.

Example

A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
C = {1, 2, 3}

# Checking for subset
is_subset = A < B  # or A.issubset(B)
print(f"A is a subset of B: {is_subset}")

# Checking for superset
is_superset = B > A  # or B.issuperset(A)
print(f"B is a superset of A: {is_superset}")

# Checking for equality
is_equal = A == C
print(f"A is equal to C: {is_equal}")

# Using <= and >= for subset and superset including equality
is_subset_or_equal = A <= C
is_superset_or_equal = B >= C
print(f"A is a subset or equal to C: {is_subset_or_equal}")
print(f"B is a superset or equal to C: {is_superset_or_equal}")

# Non-equivalence
is_not_equal = B != C
print(f"B is not equal to C: {is_not_equal}")

Output

A is a subset of B: True
B is a superset of A: True
A is equal to C: True
A is a subset or equal to C: True
B is a superset or equal to C: True
B is not equal to C: True

2. Methods of sets

Python sets come with methods that allow you to modify set elements and compare sets in various ways.

2.1 Adding and Removing Elements

Method Description
add(element) Adds an element to the set.
remove(element) Removes an element from the set. Raises a KeyError if the element is not present.
discard(element) Removes an element from the set if it is a member. If the element is not a member, does nothing.
pop() Removes and returns an arbitrary element from the set. Raises a KeyError if the set is empty.
clear() Removes all elements from the set.

2.2 Set Operations

Method Description
union(*others) Returns a new set with elements from the set and all others.
intersection(*others) Returns a new set with elements common to the set and all others.
difference(*others) Returns a new set with elements in the set that are not in the others.
symmetric_difference(other) Returns a new set with elements in either the set or other but not both.
update(*others) Updates the set, adding elements from all others.
intersection_update(*others) Updates the set, keeping only elements found in it and all others.
difference_update(*others) Updates the set, removing elements found in others.
symmetric_difference_update(other) Updates the set, keeping only elements found in either set, but not in both.

Example

A = {1, 2, 3}
B = {3, 4, 5}

# Add and remove elements
A.add(4)
A.discard(2)
print(f"After add and discard: {A}")

# Set operations
union_set = A.union(B)
intersection_set = A.intersection(B)
difference_set = A.difference(B)
print(f"Union: {union_set}")
print(f"Intersection: {intersection_set}")
print(f"Difference: {difference_set}")

Output

After add and discard: {1, 3, 4}
Union: {1, 3, 4, 5}
Intersection: {3, 4}
Difference: {1}

3. Set Comprehensions

Just like for list comprehensions, there is a support for set comprehensions as well.

Example

# Create a set of squares using set comprehension
squares = {x**2 for x in range(10)}
print(squares)

# Create a set from a list where only even numbers are stored
evens = {x for x in range(10) if x % 2 == 0}
print(evens)

Output

{0, 1, 64, 4, 36, 9, 16, 49, 81, 25}
{0, 2, 4, 6, 8}

4. frozenset() Overview

A frozenset is the immutable version of a set. Once created, items cannot be added or removed from a frozenset.

This immutability makes frozenset instances hashable, so they can be used as keys in dictionaries or as elements in other sets.

Example

immutable_set = frozenset([1, 2, 3])
print(immutable_set)

# Attempt to add an element (This will raise an error)
try:
    immutable_set.add(4)
except AttributeError as e:
    print(e)

Output

frozenset({1, 2, 3})
'frozenset' object has no attribute 'add'

5. Quiz

Question 1:

What method would you use to add an element to a set in Python?

A) push()
B) append()
C) add()
D) insert()


Question 2:

Which set method is used to remove an element that might not be present in the set?

A) remove()
B) discard()
C) pop()
D) delete()


Question 3:

What will be the result of the following code snippet?

{1, 2, 3} & {2, 3, 4}

A) {2, 3}
B) {1, 2, 3, 4}
C) {1, 4}
D) TypeError


Question 4:

Which of the following is true for the frozenset type?

A) It is mutable.
B) It can contain mutable items.
C) It can be used as a dictionary key.
D) Elements can be added to it using add().


Question 5:

What does the union() method do when applied to two sets, A and B?

A) Finds elements that are in both A and B.
B) Creates a new set with elements from both A and B, excluding duplicates.
C) Removes from A all elements that are also in B.
D) Creates a new set with elements that are unique to each set.


Question 6:

How would you remove all elements from a set A in Python?

A) A.delete()
B) A.clear()
C) A.removeAll()
D) A.discardAll()


Question 7:

Given A = {1, 2, 3} and B = {3, 4, 5}, what is the result of A - B?

A) {1, 2}
B) {3}
C) {4, 5}
D) {1, 2, 4, 5}


Question 8:

Which of the following will create a set containing the elements 1, 2, and 3?

A) set(1, 2, 3)
B) set([1, 2, 3])
C) {[1, 2, 3]}
D) {1: 'a', 2: 'b', 3: 'c'}

6. Homework

Task 1: Methods

Objective:

  1. Create two sets, A and B, where A contains numbers from 1 to 10 and B contains numbers from 5 to 15.
  2. Perform the following operations and print the results:
  3. Find the union of A and B.
  4. Find the intersection of A and B.
  5. Find the difference between A and B.
  6. Find the symmetric difference between A and B.
  7. Add a new element 16 to set B and remove element 5.
  8. Check if A is a subset of B and vice versa.

Task 2: More Methods

Objective:

  1. Create three sets, X, Y, and K, with random numbers and some common elements among them.
  2. Update set X with the intersection of X, Y, and K.
  3. Perform a symmetric difference update between set Y and set K.
  4. Check if X is now a subset of Y or K and print the result.
  5. Convert set K into an immutable set and attempt to add another element to demonstrate the immutable property.

Task 3: Guess a Letter

Objective: Create a game where players guess letters of a secret word, using sets to track guessed letters and determine the game's progress.

## Example
Input: Secret Word: "banana", Guessed Letters: {'a', 'n'}, Guess: 'b'
Output: Correct

Input: Secret Word: "apple", Guessed Letters: {'a', 'e', 'p'}, Guess: 'c'
Output: Incorrect