sets (class slides)

CSc 110 - Sets

Set methods

  • .add(value) adds an element to the set
  • .discard(value) discards the specified value
  • .union(set2) returns a set with the all elements in both sets
  • .intersection(set2) returns a set with the all elements in common

union

s1 = {1, 2, 3}
s2 = {3, 4, 5}
s1.union(s2)
{1, 2, 3, 4, 5}

union

intersection

s1 = {1, 2, 3}
s2 = {3, 4, 5}
s1.intersection(s2)
{3}

intersection

Evaluate the code

presences = {"Anna", "Beatrice", "Claude"}
absences = {"Elvin", "Harley"}
absences.add("Becca")
presences.union(absences)

task_1 = {"Anna", "Beatrice", "Claude"}
task_2 = {"Anna", "Elvin", "Harley", "Beatrice"}
task_1.intersection(task_2)

task_2.discard("Anna")
task_1.intersection(task_2)

Evaluate the code

presences = {"Anna", "Beatrice", "Claude"}
absences = {"Elvin", "Harley"}
absences.add("Becca")
presences.union(absences)
{'Anna', 'Beatrice', 'Becca', 'Claude', 'Elvin', 'Harley'}
task_1 = {"Anna", "Beatrice", "Claude"}
task_2 = {"Anna", "Elvin", "Harley", "Beatrice"}
task_1.intersection(task_2)
{'Anna', 'Beatrice'}
task_2.discard("Anna")
task_1.intersection(task_2)
{'Beatrice'}

Write a function

  1. Its name is common_values
  2. It takes two sets are arguments
  3. It returns False if the sets have no elements in common, True otherwise
assert common_values({1, 2, 3}, {3, 4, 5}) == True
assert common_values({1, 2, 3}, {30, 40, 50}) == False

Write a function – solution

def common_values(set_1, set_2):
  return len(set_1.intersection(set_2)) != 0

if __name__ == "__main__":
  assert common_values({1, 2, 3}, {3, 4, 5}) == True
  assert common_values({1, 2, 3}, {30, 40, 50}) == False
  print("Passed tests.")
Passed tests.

Write a function

  1. Function name is discard_elements
  2. It takes two sets as argument: set_1 and set_2
  3. It mutates the first set (set_1) removing all elements it has in common with set_2
test_set = {1, 2, 3, 4}
discard_elements(test_set, {2})
assert test_set == {1, 3, 4}

Write a function – solution

def discard_elements(set_1, set_2):
  to_remove = set_1.intersection(set_2)
  for value in to_remove:
    set_1.discard(value)
    
if __name__ == "__main__":
  test_set = {1, 2, 3, 4}
  discard_elements(test_set, {2})
  assert test_set == {1, 3, 4}
  print(test_set)
{1, 3, 4}