Use a Função len()
Na etapa anterior, você aprendeu como obter o tamanho de um conjunto usando a função len(). Nesta etapa, exploraremos maneiras mais avançadas de usar a função len() com conjuntos, incluindo o uso dentro de instruções condicionais e loops.
Vamos começar modificando nosso script set_size.py para incluir uma instrução condicional que verifica se o conjunto está vazio. Abra seu arquivo set_size.py no editor VS Code e modifique-o da seguinte forma:
## Create a set of numbers
my_set = {1, 2, 3, 4, 5}
## Print the set
print(my_set)
## Get the size of the set using the len() function
set_size = len(my_set)
## Print the size of the set
print("The size of the set is:", set_size)
## Check if the set is empty
if set_size == 0:
print("The set is empty.")
else:
print("The set is not empty.")
Salve o arquivo e execute-o:
python set_size.py
Você deve ver a seguinte saída:
{1, 2, 3, 4, 5}
The size of the set is: 5
The set is not empty.
Agora, vamos modificar o script para criar um conjunto vazio e verificar seu tamanho. Altere a primeira linha do seu script set_size.py para criar um conjunto vazio:
## Create an empty set
my_set = set()
## Print the set
print(my_set)
## Get the size of the set using the len() function
set_size = len(my_set)
## Print the size of the set
print("The size of the set is:", set_size)
## Check if the set is empty
if set_size == 0:
print("The set is empty.")
else:
print("The set is not empty.")
Salve o arquivo e execute-o novamente:
python set_size.py
Desta vez, você deve ver a seguinte saída:
set()
The size of the set is: 0
The set is empty.
Como você pode ver, a função len() retorna 0 para um conjunto vazio, e nossa instrução condicional identifica corretamente que o conjunto está vazio.
Agora, vamos usar a função len() em um loop. Suponha que queremos remover elementos de um conjunto até que ele esteja vazio. Modifique seu script set_size.py da seguinte forma:
## Create a set of numbers
my_set = {1, 2, 3, 4, 5}
## Print the set
print(my_set)
## Remove elements from the set until it is empty
while len(my_set) > 0:
## Remove an arbitrary element from the set
element = my_set.pop()
print("Removed element:", element)
print("The set is now:", my_set)
print("The set is now empty.")
Salve o arquivo e execute-o:
python set_size.py
Você deve ver uma saída semelhante à seguinte (a ordem dos elementos removidos pode variar):
{1, 2, 3, 4, 5}
Removed element: 1
The set is now: {2, 3, 4, 5}
Removed element: 2
The set is now: {3, 4, 5}
Removed element: 3
The set is now: {4, 5}
Removed element: 4
The set is now: {5}
Removed element: 5
The set is now: set()
The set is now empty.
Neste exemplo, usamos a função len() para verificar se o conjunto está vazio em cada iteração do loop while. O método pop() remove um elemento arbitrário do conjunto. O loop continua até que o conjunto esteja vazio.