Elemento más frecuente

PythonPythonBeginner
Practicar Ahora

This tutorial is from open-source community. Access the source code

💡 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 desafío, se te pide escribir una función de Python que tome una lista de enteros como entrada y devuelva el elemento más frecuente de la lista.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/numeric_types("Numeric Types") python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/variables_data_types -.-> lab-13697{{"Elemento más frecuente"}} python/numeric_types -.-> lab-13697{{"Elemento más frecuente"}} python/comments -.-> lab-13697{{"Elemento más frecuente"}} python/lists -.-> lab-13697{{"Elemento más frecuente"}} python/tuples -.-> lab-13697{{"Elemento más frecuente"}} python/function_definition -.-> lab-13697{{"Elemento más frecuente"}} python/build_in_functions -.-> lab-13697{{"Elemento más frecuente"}} python/data_collections -.-> lab-13697{{"Elemento más frecuente"}} end

Elemento más frecuente

Escribe una función de Python llamada most_frequent(lst) que tome una lista de enteros como entrada y devuelva el elemento más frecuente de la lista. Si hay múltiples elementos que aparecen el mismo número de veces y tienen la frecuencia más alta, devuelve el que aparece primero en la lista.

Para resolver este problema, puedes seguir estos pasos:

  1. Utiliza set() para obtener los valores únicos en lst.
  2. Utiliza max() para encontrar el elemento que tiene más apariciones.

Tu función debe tener la siguiente firma:

def most_frequent(lst: List[int]) -> int:
def most_frequent(lst):
  return max(set(lst), key = lst.count)
most_frequent([1, 2, 1, 2, 3, 2, 1, 4, 2]) #2

Resumen

En este desafío, has aprendido cómo encontrar el elemento más frecuente en una lista de enteros utilizando Python. También has aprendido cómo utilizar las funciones set() y max() para resolver este problema.