Питхон скупови: детаљан визуелни увод

Добродошли

У овом чланку ћете научити основе скупова у Питхону. Ово је врло моћан уграђени тип података који можете користити у својим Питхон пројектима.

Истражићемо:

  • Који су то скупови и зашто су релевантни за ваше пројекте.
  • Како створити сет.
  • Како проверити да ли је елемент у скупу.
  • Разлика између скупова и фрозенсета.
  • Како радити са скуповима (у овом делу ћемо заронити у основе теорије скупова).
  • Како додати и уклонити елементе из скупова и како их обрисати.

Почнимо! ⭐

Етс Комплети у контексту

Дозволите ми да вам кажем зашто бисте желели да користите скупове у својим пројектима. У математици, скуп је скуп различитих предмета. У Питхону, оно што их чини толико посебним је чињеница да немају дуплиране елементе , тако да се могу користити за ефикасно уклањање дуплираних елемената са списка и корпица.

Према Питхон документацији:

Питхон такође укључује тип података за скупове . Скуп је неуређена колекција без дуплираних елемената. Основне употребе укључују тестирање чланства и уклањање дуплираних уноса.

❗Важно: Елементи скупа морају бити непроменљиви (не могу се мењати). Непроменљиви типови података укључују низове, корпице и бројеве као што су цели бројеви и пловци.

? Синтакса

Да бисмо креирали скуп, започињемо писањем пар коврџатих заграда, {}а у те коврџаве заграде укључујемо елементе скупа одвојене зарезом и размаком.  

? Савет: Обратите пажњу да се ова синтакса разликује од Питхон речника јер не стварамо парове кључ / вредност, већ поједине елементе укључујемо у коврџаве заграде {}.

Комплет()

Алтернативно, можемо користити функцију сет () за стварање скупа (погледајте доле).

Да бисмо то урадили, проследили бисмо итерабил (на пример, листу, низ или тупле) и овај итерабил би се претворио у скуп, уклањајући све дупликате елемената.

Ово је пример у ИДЛЕ-у:

# Set >>> {1, 2, 3, 4} {1, 2, 3, 4} # From a list >>> set([1, 2, 3, 4]) {1, 2, 3, 4} # From a tuple >>> set((1, 2, 3, 4)) {1, 2, 3, 4}

? Савет: Да бисте креирали празан скуп, морате да користите функцију сет () јер ће се употребом празног скупа витичастих заграда, попут овог {}, аутоматски створити празан речник , а не празан скуп.

# Creates a dictionary, not a set. >>> type({})  # This is a set >>> type(set()) 

Уп Двоструки елементи су уклоњени

Ако итерабил који прослеђујете као аргумент set()има дупликате елемената, они се уклањају ради стварања скупа.

На пример, приметите како се уклањају дуплицирани елементи када прођемо ову листу:

>>> a = [1, 2, 2, 2, 2, 3, 4, 1, 4] >>> set(a) {1, 2, 3, 4}

и приметите како се дуплицирани знакови уклањају када проследимо овај низ:

>>> a = "hhheeelllooo" >>> set(a) {'e', 'l', 'o', 'h'}

? Дужина

Да бисте пронашли дужину скупа, можете да користите уграђену функцију лен ():

>>> a = {1, 2, 3, 4} >>> b = set(a) >>> len(b) 4

У математици се број елемената скупа назива „ кардиналност “ скупа.

Те Тестирање чланства

Можете да тестирате да ли је неки елемент у скупу са inоператором:

Ово у примеру:

>>> a = "hhheeelllooo" >>> b = set(a) >>> b {'e', 'l', 'o', 'h'} # Test if the characters 'e' and 'a' are in set b >>> 'e' in b True >>> 'a' in b False

? Сетови против Фрозенсетс-а

Сетови су променљиви, што значи да се могу модификовати након што су дефинисани.

Према Питхон документацији:

setТип је променљиво - садржај може мењати користећи методе као add()и remove(). Будући да је променљив, нема хеш вредност и не може се користити ни као кључ речника ни као елемент другог скупа.

Будући да не могу садржати вредности променљивих типова података, ако покушамо да створимо скуп који садржи скупове као елементе (угнежђени скупови), видећемо ову грешку:

TypeError: unhashable type: 'set' 

Ово је пример у ИДЛЕ-у. Приметите како су елементи које покушавамо да укључимо:

>>> a = {{1, 2, 3}, {1, 2, 4}} Traceback (most recent call last): File "", line 1, in  a = {{1, 2, 3}, {1, 2, 4}} TypeError: unhashable type: 'set'

Фрозенсетс

Да бисмо решили овај проблем, имамо још један тип скупа који се назива фрозенсетс.

Они су непроменљиви , таконе могу се мењати и можемо их користити за стварање угнежђених скупова.

Према Питхон документацији:

frozensetТип је непроменљив и хасхабле - њен садржај не може бити измењен након што је створио; стога се може користити као кључ речника или као елемент другог скупа.

Да бисмо креирали замрзнути сет, користимо:

? Савет: Можете створити празан замрзнути сет помоћу frozenset().

Ово је пример скупа који садржи два фрозенсета:

>>> a = {frozenset([1, 2, 3]), frozenset([1, 2, 4])} >>> a {frozenset({1, 2, 3}), frozenset({1, 2, 4})}

Приметите да не добијамо грешке и скуп је успешно направљен.

? Увод у теорију скупова

Пре него што зађемо у скупове операција, морамо истражити мало теорије скупова и Венов дијаграм. Заронит ћемо у сваку постављену операцију са одговарајућим еквивалентом у Питхон коду. Почнимо.

Subsets and Supersets

You can think of a subset as a "smaller portion" of a set. That is how I like to think about it. If you take some of the elements of a set and make a new set with those elements, the new set is a subset of the original set.

It's as if you had a bag full of rubber balls of different colors. If you make a set with all the rubber balls in the bag, and then take some of those rubber balls and make a new set with them, the new set is a subset of the original set.

Let me illustrate this graphically. If we have a set A with the elements 1, 2, 3, 4:

>>> a = {1, 2, 3, 4}

We can "take" or "select" some elements of a and make a new set called B. Let's say that we chose to include the elements 1 and 2 in set B:

>>> a = {1, 2, 3, 4} >>> b = {1, 2}

Every element of B is in A. Therefore, B is a subset of A.

This can be represented graphically like this, where the new set B is illustrated in yellow:

? Note: In set theory, it is a convention to use uppercase letters to denote sets. This is why I will use them to refer to the sets (A and B), but I will use lowercase letter in Python (a and b).

.issubset()

We can check if B is a subset of A with the method .issubset():

>>> a = {1, 2, 3, 4} >>> b = {1, 2} >>> b.issubset(a) True

As you can see, B is a subset of A because the value returned is True.

But the opposite is not true since not all the element of A are in B:

>>> a.issubset(b) False

Let's see something very interesting:

>>> a = {1, 2, 3, 4} >>> b = {1, 2, 3, 4} >>> a.issubset(b) True >>> b.issubset(a) True

If two sets are equal, one is a subset of the other and vice versa because all the elements of A are in B and all elements of B are in A. This can be illustrated like this:

Using <=

We can achieve the same functionality of the .issubset() method with the <= comparison operator:

>>> a = {1, 2, 3, 4} >>> b = {1, 2, 3, 4} >>> a <= b True

This operator returns True if the left operand is a subset of the right operand, even when the two sets are equal (when they have the same elements).

Proper Subset

But what happens if we want to check if a set is a proper subset of another? A proper subset is a subset that is not equal to the set (does not have all the same elements).

This would be a graphical example of a proper subset. B does not have all the elements of A:

To check this, we can use the < comparison operator:

# B is not a proper subset of A because B is equal to A >>> a = {1, 2, 3, 4} >>> b = {1, 2, 3, 4} >>> b >> a = {1, 2, 3, 4} >>> b = {1, 2} >>> b < a True

Superset

If B is a subset of A, then A is a superset of B. A superset is the set that contains all the elements of the subset.  

This can be illustrated like this (see below), where A is a superset of B:

.issuperset()

We can test if a set is a superset of another with the .issuperset() method:

>>> a = {1, 2, 3, 4} >>> b = {1, 2} >>> a.issuperset(b) True

We can also use the operators > and >=. They work exactly like < and <=, but now they determine if the left operand is a superset of the right operand:

>>> a = {1, 2, 3, 4} >>> b = {1, 2} >>> a > b True >>> a >= b True

Disjoint Sets

Two sets are disjoint if they have no elements in common. For example, here we have two disjoint sets:

.isdisjoint()

We can check if two sets are disjoint with the .isdisjoint() method:

# Elements in common: 3, 1 >>> a = {3, 6, 1} >>> b = {2, 8, 3, 1} >>> a.isdisjoint(b) False # Elements in common: None >>> a = {3, 1, 4} >>> b = {8, 9, 0} >>> a.isdisjoint(b) True

? Set Operations

We can operate on sets to create new sets, following the rules of set theory. Let's explore these operations.

Union

This is the first operation that we will analyze. It creates a new set that contains all the elements of the two sets (without repetition).

This is an example:

>>> a = {3, 1, 7, 4} >>> b = {2, 8, 3, 1} >>> a | b {1, 2, 3, 4, 7, 8}

? Tip: We can assign this new set to a variable, like this:

>>> a = {3, 1, 7, 4} >>> b = {2, 8, 3, 1} >>> c = a | b >>> c {1, 2, 3, 4, 7, 8}

In a diagram, these sets could be represented like this (see below). This is called a Venn diagram, and it is used to illustrate the relationships between sets and the result of set operations.

We can easily extend this operation to work with more than two sets:

>>> a = {3, 1, 7, 4} >>> b = {2, 8, 3, 1} >>> c = {1, 0, 4, 6} >>> d = {8, 2, 6, 3} # Union of these four sets >>> a | b | c | d {0, 1, 2, 3, 4, 6, 7, 8}

? Tip: If the union contains repeated elements, only one is included in the final set to eliminate repetition.

Intersection

The intersection between two sets creates another set that contains all the elements that are inboth A and B.

This is an example:

>>> a = {3, 6, 1} >>> b = {2, 8, 3, 1} >>> a & b {1, 3}

The Venn diagram for the intersection operation would be like this (see below), because only the elements that are in both A and B are included in the resulting set:

We can easily extend this operation to work with more than two sets:

>>> a = {3, 1, 7, 4, 5} >>> b = {2, 8, 3, 1, 5} >>> c = {1, 0, 4, 6, 5} >>> d = {8, 2, 6, 3, 5} # Only 5 is in a, b, c, and d. >>> a & b & c & d {5}

Difference

The difference between set A and set B is another set that contains all the elements of set A that are not in set B.

This is an example:

>>> a = {3, 6, 1} >>> b = {2, 8, 3, 1} >>> a - b {6}

The Venn diagram for this difference would be like this (see below), because only the elements of A that are not in B are included in the resulting set:

? Tip: Notice how we remove the elements of A that are also in B (in the intersection).

We can easily extend this to work with more than two sets:

>>> a = {3, 1, 7, 4, 5} >>> b = {2, 8, 3, 1, 5} >>> c = {1, 0, 4, 6, 5} # Only 7 is in A but not in B and not in C >>> a - b - c {7}

Symmetric Difference

The symmetric difference between two sets A and B is another set that contains all the elements that are in either A or B, but not both. We basically remove the elements from the intersection.

>>> a = {3, 6, 1} >>> b = {2, 8, 3, 1} >>> a ^ b {2, 6, 8}

The Venn diagram for the symmetric difference would be like this (see below), because only the elements that are in either A or B, but not both, are included in the resulting set:

We can easily extend this to work with more than two sets:

>>> a = {3, 1, 7, 4, 5} >>> b = {2, 8, 3, 1, 5} >>> c = {1, 0, 4, 6, 5} >>> d = {8, 2, 6, 3, 5} >>> a ^ b ^ c ^ d {0, 1, 3, 7}

Update Sets Automatically

If you want to update set A immediately after performing these operations, you can simply add an equal sign after the operator. For example:

>>> a = {1, 2, 3, 4} >>> b = {1, 2} # Notice the &= >>> a &= b >>> a {1, 2}

We are assigning the set that results from a & b to set a in just one line. You can do the same with the other operators: ^= , |=, and -=.

? Tip: This is very similar to the syntax that we use with variables (for example: a += 5) but now we are working with sets.

? Set Methods

Sets include helpful built-in methods to help us perform common and essential functionality such as adding elements, deleting elements, and clearing the set.

Add Elements

To add elements to a set, we use the .add() method, passing the element as the only argument.

>>> a = {1, 2, 3, 4} >>> a.add(7) >>> a {1, 2, 3, 4, 7}

Delete Elements

There are three ways to delete an element from a set: .remove() ,.discard(), and .pop(). They have key differences that we will explore.

The first two methods (.remove() and .discard()) work exactly the same when the element is in the set. The new set is returned:

>>> a = {1, 2, 3, 4} >>> a.remove(3) >>> a {1, 2, 4} >>> a = {1, 2, 3, 4} >>> a.discard(3) >>> a {1, 2, 4}

The key difference between these two methods is that if we use the .remove() method, we run the risk of trying to remove an element that doesn't exist in the set and this will raise a KeyError:

>>> a = {1, 2, 3, 4} >>> a.remove(5) Traceback (most recent call last): File "", line 1, in  a.remove(5) KeyError: 5

We will never have that problem with .discard() since it doesn't raise an exception if the element is not found. This method will simply leave the set intact, as you can see in this example:

>>> a = {1, 2, 3, 4} >>> a.discard(5) >>> a {1, 2, 3, 4}

The third method (.pop()) will remove and return an arbitrary element from the set and it will raise a KeyError if the set is empty.

>>> a = {1, 2, 3, 4} >>> a.pop() 1 >>> a.pop() 2 >>> a.pop() 3 >>> a {4} >>> a.pop() 4 >>> a set() >>> a.pop() Traceback (most recent call last): File "", line 1, in  a.pop() KeyError: 'pop from an empty set'

Clear the Set

You can use the .clear() method if you need to delete all the elements from a set. For example:

>>> a = {1, 2, 3, 4} >>> a.clear() >>> a set() >>> len(a) 0

? In Summary

  • Sets are unordered built-in data types that don't have any repeated elements, so they allow us to eliminate repeated elements from lists and tuples.
  • They are mutable and they can only contain immutable elements.
  • We can check if a set is a subset or superset of another set.
  • Frozenset is an immutable type of set that allows us to create nested sets.
  • We can operate on sets with: union (|), intersection (&), difference (-), and symmetric difference (^).
  • We can add elements to a set, delete them, and clear the set completely using built-in methods.

I really hope you liked my article and found it helpful. Now you can work with sets in your Python projects. Check out my online courses. Follow me on Twitter. ⭐️