Python. Sets (Множество)
Python · Sets
Sets / Множества

Store unique values, check membership and change a collection one element at a time.

Learning objectives
  • 11.2.1.1 create sets
  • 11.2.1.2 manipulate sets by adding, removing, and counting elements

1. What is a set?

A set is an unordered collection of distinct elements. Repeated equal values are stored only once.

  • A set can be changed: you can add and remove elements.
  • The order of its elements is not guaranteed.
  • A set does not record element positions.
  • You can check membership and visit each element in a loop.

Create an empty or non-empty set

empty_set = set()
colours = {"red", "yellow", "green"}
numbers = {4, 4, 7, 2, 7}

print(empty_set) # set()
print(len(numbers)) # 3
Common mistake. To create an empty set, use set(), not {}.

Create a set from text

When a string is passed to set(), its distinct characters become the elements.

letters = set("banana")
print(len(letters)) # 3: the distinct letters are a, b and n

The elements of a set may have different types, such as numbers and strings.

mixed_set = {7, "seven", 2.5} # valid

Use numeric sets for the calculations below.

2. Read, check and count

Count elements and calculate statistics

numbers = {5, 3, 7, 4}

print(len(numbers)) # 4: number of distinct elements
print(sum(numbers)) # 19: sum of the numbers
print(min(numbers)) # 3: minimum
print(max(numbers)) # 7: maximum
Empty sets. len(set()) and sum(set()) return 0. Calling min(set()) or max(set()) without a default value raises ValueError.
numbers = set()
if numbers:
 print(min(numbers))
else:
 print("The set is empty")

Check whether an element is present

fruits = {"apple", "orange", "lemon"}
item = "orange"

if item in fruits:
 print("The item is in the set")
else:
 print("The item is not in the set")

print("melon" not in fruits) # True

Loop through a set

numbers = {2, 4, 7}

for number in numbers:
 print(number) # each element is visited; the order is not guaranteed
Keep the size unchanged during iteration. Do not add or delete elements in the same set while looping through it.

Display a set

Use print() to display the elements. Their order is not guaranteed.

numbers = {7, 2, 4}
print(numbers) # all three elements are displayed

3. Add and remove elements

Add one element: add()

members = set()
members.add(101)
members.add(104)
members.add(101) # already present: the set does not change

print(len(members)) # 2

Choose the correct deletion method

Method Action If the element is missing / set is empty
s.discard(x) Remove x if it is present. Do nothing if x is missing.
s.remove(x) Remove x. Raise KeyError if x is missing.
s.pop() Remove and return one arbitrary element. Raise KeyError if the set is empty.
s.clear() Remove all elements. An empty set remains empty.

discard(): absence is acceptable

members = {101, 104, 108}
members.discard(104)
members.discard(999) # no error
print(len(members)) # 2

remove(): check if needed

members = {101, 104, 108}
student_id = 104
if student_id in members:
 members.remove(student_id)
# members.remove(999) raises KeyError

pop(): keep the returned element

tokens = {10, 20, 30}
token = tokens.pop()

print(token in tokens) # False
print(len(tokens)) # 2

Do not rely on a particular value being returned. pop() removes one available element without promising an order or a random selection.

clear(): start again

members = {101, 104}
members.clear()
print(members) # set()

members.add(109)
print(len(members)) # 1
Do not replace a set with a method result. add(), discard(), remove() and clear() return None after a successful call. Write members.add(110), not members = members.add(110).

4. Set laboratory

Apply an action and compare the set before and after it. This lab uses integers only.

numbers — displayed in ascending order for readability{2, 4, 7}len(numbers) = 3
Try adding 5 twice, then compare discard(99) with remove(99).

The lab demonstrates these actions. It does not execute arbitrary Python code. Its choice for pop() is just one possible choice.

5. Exercises

There are 8 exercises: the embedded warm-up and 7 checked tasks about sets. Check an answer, use a hint if needed, and read the explanation.

Ex. 1 · Calculate results

If the embedded activity does not load, open it on LearningApps. Its results are separate from the progress shown below.

Completed: 0 / 7 tasks

Answers and progress are saved in this browser on this device. They are not sent to a teacher.

Interactive checks require JavaScript. If this notice remains visible, open the page in a browser with JavaScript enabled.

Ex. 2 · Create a setCreation · properties · Not checked

Choose the correct construction or description in each case.

Select all correct statements.
 
Show explanation

set(); 3; True. Select the first three statements. A set has unique elements, is unordered and can be changed.

Ex. 3 · Unique number statisticslen · sum · min · max · Not checked

Predict the four results for this set.

numbers = {4, 4, 7, 2, 7}
print(len(numbers))
print(sum(numbers))
print(min(numbers))
print(max(numbers))
 
Show explanation

The set contains 2, 4 and 7. The results are 3, 13, 2, 7, in that order.

Ex. 4 · Access checkin · not in · element types · Not checked

Predict each Boolean result. The final line uses a string.

members = {101, 104}
print(104 in members)
print(109 not in members)
print("101" in members)
 
Show explanation

True, True, False. 104 is present, 109 is absent, and the string "101" is not an element of the set.

Ex. 5 · Add, clear and countadd · clear · duplicate values · Not checked

Write the size after each change to the set.

visited = set()
visited.add(7)
print(len(visited))
visited.add(7)
print(len(visited))
visited.clear()
print(len(visited))
visited.add(3)
print(len(visited))
 
Show explanation

1, 1, 0, 1. The second 7 adds nothing new. clear() empties the set, and add(3) puts one element into it.

Ex. 6 · Choose a deletion methoddiscard · remove · clear · Not checked

Choose the method that matches each requirement.

members = {2, 4, 6}
members.discard(4)
members.discard(9)
print(len(members))
 
Show explanation

discard(), remove(), clear(); 2. The set ends with elements 2 and 6.

Ex. 7 · Understand pop()Arbitrary element · return value · Not checked

The set is non-empty. Select everything that must be true after the code runs.

tokens = {10, 20, 30}
token = tokens.pop()
Select all correct statements.
 
Show explanation

Select the first three statements. Calling pop() on an empty set raises KeyError.

Ex. 8 · Loop through unique valuesfor · condition · accumulation · Not checked

Predict the number and sum of the distinct even values.

values = {2, 2, 3, 6, 8, 8}
count = 0
total = 0
for value in values:
 if value % 2 == 0:
   count += 1
 total += value
print(count)
print(total)
 
Show explanation

The even elements are 2, 6 and 8. The program prints 3 and then 16.

Категория: Algorithms | Добавил: bzfar77 (28.10.2021)
Просмотров: 12212 | Теги: Set, Python, data structure, data type | Рейтинг: 5.0/10
Всего комментариев: 0
avatar