N Max Elements | Challenge

PythonPythonBeginner
Practice Now

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

Introduction

In Python, there are many ways to manipulate lists. One common task is to find the n maximum elements from a list. In this challenge, you will be asked to write a function that returns the n maximum elements from a list.


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/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13156{{"`N Max Elements | Challenge`"}} python/booleans -.-> lab-13156{{"`N Max Elements | Challenge`"}} python/lists -.-> lab-13156{{"`N Max Elements | Challenge`"}} python/tuples -.-> lab-13156{{"`N Max Elements | Challenge`"}} python/function_definition -.-> lab-13156{{"`N Max Elements | Challenge`"}} python/default_arguments -.-> lab-13156{{"`N Max Elements | Challenge`"}} python/build_in_functions -.-> lab-13156{{"`N Max Elements | Challenge`"}} end

N Max Elements Challenge

Problem

Write a function max_n(lst, n = 1) that takes a list lst and an optional integer n as arguments and returns a list of the n maximum elements from the provided list. If n is not provided, the function should return a list containing the maximum element of the list. If n is greater than or equal to the length of the list, the function should return the original list sorted in descending order.

Your task is to implement the max_n() function.

Example

max_n([1, 2, 3]) ## [3]
max_n([1, 2, 3], 2) ## [3, 2]
max_n([1, 2, 3, 4, 5], 3) ## [5, 4, 3]
max_n([1, 2, 3, 4, 5], 6) ## [5, 4, 3, 2, 1]

Summary

In this challenge, you have learned how to find the n maximum elements from a list in Python. You have implemented a function that takes a list and an optional integer as arguments and returns a list of the n maximum elements from the provided list.

Other Python Tutorials you may like