Cómo comprobar si un conjunto (set) tiene un tamaño determinado en Python

PythonPythonBeginner
Practicar Ahora

💡 Este tutorial está traducido por IA desde la versión en inglés. Para ver la versión original, puedes hacer clic aquí

Introducción

En este laboratorio, aprenderás cómo verificar si un conjunto (set) tiene un tamaño determinado en Python. El laboratorio se centra en el uso de la función len() para determinar el número de elementos en un conjunto, lo cual es esencial para diversas tareas de programación.

Comenzarás creando un conjunto de números y cadenas en un script de Python y luego usarás la función len() para encontrar el tamaño del conjunto. Finalmente, compararás el tamaño del conjunto con un tamaño deseado para verificar si coinciden.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/while_loops("While Loops") python/DataStructuresGroup -.-> python/sets("Sets") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/ModulesandPackagesGroup -.-> python/using_packages("Using Packages") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/conditional_statements -.-> lab-559562{{"Cómo comprobar si un conjunto (set) tiene un tamaño determinado en Python"}} python/while_loops -.-> lab-559562{{"Cómo comprobar si un conjunto (set) tiene un tamaño determinado en Python"}} python/sets -.-> lab-559562{{"Cómo comprobar si un conjunto (set) tiene un tamaño determinado en Python"}} python/build_in_functions -.-> lab-559562{{"Cómo comprobar si un conjunto (set) tiene un tamaño determinado en Python"}} python/using_packages -.-> lab-559562{{"Cómo comprobar si un conjunto (set) tiene un tamaño determinado en Python"}} python/data_collections -.-> lab-559562{{"Cómo comprobar si un conjunto (set) tiene un tamaño determinado en Python"}} end

Comprender el tamaño de un conjunto (set)

En este paso, aprenderás cómo determinar el número de elementos en un conjunto (set) utilizando la función len(). Comprender el tamaño de un conjunto es crucial para diversas tareas de programación, como verificar si un conjunto está vacío o comparar los tamaños de diferentes conjuntos.

Primero, creemos un conjunto simple en un script de Python. Abre tu editor de VS Code en el entorno de LabEx y crea un nuevo archivo llamado set_size.py en el directorio ~/project.

## Create a set of numbers
my_set = {1, 2, 3, 4, 5}

## Print the set
print(my_set)

Guarda el archivo. Ahora, ejecutemos este script para ver la salida. Abre la terminal en VS Code (puedes encontrarla en el panel inferior) y navega hasta el directorio ~/project (por defecto ya deberías estar allí). Ejecuta el script utilizando el siguiente comando:

python set_size.py

Deberías ver la siguiente salida:

{1, 2, 3, 4, 5}

Ahora que tenemos un conjunto, descubramos cuántos elementos contiene. Agrega las siguientes líneas a tu script set_size.py:

## 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)

Guarda los cambios y ejecuta el script nuevamente:

python set_size.py

Esta vez, deberías ver la siguiente salida:

{1, 2, 3, 4, 5}
The size of the set is: 5

La función len() devuelve el número de elementos en el conjunto. En este caso, nuestro conjunto my_set contiene 5 elementos.

Intentemos otro ejemplo con un conjunto de cadenas. Modifica tu script set_size.py para que sea el siguiente:

## Create a set of strings
my_set = {"apple", "banana", "cherry"}

## 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)

Guarda el archivo y ejecútalo:

python set_size.py

Deberías ver la siguiente salida:

{'cherry', 'banana', 'apple'}
The size of the set is: 3

Como puedes ver, la función len() funciona con conjuntos que contienen diferentes tipos de datos.

Usar la función len()

En el paso anterior, aprendiste cómo obtener el tamaño de un conjunto (set) utilizando la función len(). En este paso, exploraremos formas más avanzadas de usar la función len() con conjuntos, incluyendo su uso dentro de declaraciones condicionales y bucles.

Comencemos modificando nuestro script set_size.py para incluir una declaración condicional que verifique si el conjunto está vacío. Abre tu archivo set_size.py en el editor de VS Code y modifícalo de la siguiente manera:

## 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.")

Guarda el archivo y ejecútalo:

python set_size.py

Deberías ver la siguiente salida:

{1, 2, 3, 4, 5}
The size of the set is: 5
The set is not empty.

Ahora, modifiquemos el script para crear un conjunto vacío y verificar su tamaño. Cambia la primera línea de tu script set_size.py para crear un conjunto vacío:

## 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.")

Guarda el archivo y ejecútalo nuevamente:

python set_size.py

Esta vez, deberías ver la siguiente salida:

set()
The size of the set is: 0
The set is empty.

Como puedes ver, la función len() devuelve 0 para un conjunto vacío, y nuestra declaración condicional identifica correctamente que el conjunto está vacío.

Ahora, usemos la función len() en un bucle. Supongamos que queremos eliminar elementos de un conjunto hasta que esté vacío. Modifica tu script set_size.py de la siguiente manera:

## 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.")

Guarda el archivo y ejecútalo:

python set_size.py

Deberías ver una salida similar a la siguiente (el orden de los elementos eliminados puede 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.

En este ejemplo, usamos la función len() para verificar si el conjunto está vacío en cada iteración del bucle while. El método pop() elimina un elemento arbitrario del conjunto. El bucle continúa hasta que el conjunto está vacío.

Comparar con el tamaño deseado

En este paso, aprenderás cómo comparar el tamaño de un conjunto (set) con un tamaño deseado utilizando declaraciones condicionales. Esto es útil cuando necesitas asegurarte de que un conjunto contenga un número específico de elementos antes de realizar ciertas operaciones.

Modifiquemos nuestro script set_size.py para comparar el tamaño de un conjunto con un tamaño deseado. Abre tu archivo set_size.py en el editor de VS Code y modifícalo de la siguiente manera:

## Create a set of numbers
my_set = {1, 2, 3}

## 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)

## Define the desired size
desired_size = 5

## Compare the size of the set with the desired size
if set_size == desired_size:
    print("The set has the desired size.")
elif set_size < desired_size:
    print("The set is smaller than the desired size.")
else:
    print("The set is larger than the desired size.")

Guarda el archivo y ejecútalo:

python set_size.py

Deberías ver la siguiente salida:

{1, 2, 3}
The size of the set is: 3
The set is smaller than the desired size.

Ahora, modifiquemos el script para crear un conjunto con el tamaño deseado. Cambia la primera línea de tu script set_size.py para crear un conjunto con 5 elementos:

## 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)

## Define the desired size
desired_size = 5

## Compare the size of the set with the desired size
if set_size == desired_size:
    print("The set has the desired size.")
elif set_size < desired_size:
    print("The set is smaller than the desired size.")
else:
    print("The set is larger than the desired size.")

Guarda el archivo y ejecútalo nuevamente:

python set_size.py

Esta vez, deberías ver la siguiente salida:

{1, 2, 3, 4, 5}
The size of the set is: 5
The set has the desired size.

Finalmente, modifiquemos el script para crear un conjunto mayor que el tamaño deseado. Cambia la primera línea de tu script set_size.py para crear un conjunto con 7 elementos:

## Create a set of numbers
my_set = {1, 2, 3, 4, 5, 6, 7}

## 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)

## Define the desired size
desired_size = 5

## Compare the size of the set with the desired size
if set_size == desired_size:
    print("The set has the desired size.")
elif set_size < desired_size:
    print("The set is smaller than the desired size.")
else:
    print("The set is larger than the desired size.")

Guarda el archivo y ejecútalo:

python set_size.py

Deberías ver la siguiente salida:

{1, 2, 3, 4, 5, 6, 7}
The size of the set is: 7
The set is larger than the desired size.

Esto demuestra cómo usar la función len() para comparar el tamaño de un conjunto con un tamaño deseado y realizar diferentes acciones basadas en la comparación.

Resumen

En este laboratorio (lab), aprendiste cómo determinar el tamaño de un conjunto (set) de Python utilizando la función len(). Creaste un script de Python llamado set_size.py y lo llenaste con conjuntos que contenían números y cadenas de texto (strings). Luego, se utilizó la función len() para obtener la cantidad de elementos dentro de cada conjunto, demostrando su aplicación con diferentes tipos de datos.

El laboratorio implicó crear conjuntos, imprimir su contenido y luego utilizar len() para obtener e imprimir el tamaño del conjunto. Este proceso se repitió tanto con un conjunto de enteros como con un conjunto de cadenas de texto, reforzando la comprensión de cómo utilizar eficazmente la función len() para determinar la cantidad de elementos en un conjunto.