Lesson·difficulty 2/5·~12 min
Lists: top N values
Read the task → edit your code → Run to see the output → Run tests to check your answer.
Lists
Lists hold multiple values in order:
python
fruit = ["apple", "banana", "cherry"]
fruit[0] # "apple" — indices start at 0
fruit[-1] # "cherry" — negative counts from the end
fruit.append("kiwi")
len(fruit) # 4
You can iterate over a list with for:
python
for item in fruit:
print(item)
Your task
Write a function top_n(values, n) that returns the n largest numbers
from values, sorted from largest to smallest.
If n is greater than len(values), return all of them sorted.
python
top_n([3, 1, 4, 1, 5, 9, 2, 6], 3) # [9, 6, 5]
top_n([], 5) # []
top_n([1, 2, 3], 10) # [3, 2, 1]
Hint: if the numbers were ordered largest-first, the answer would be sitting
right at the front of the list. Two moves: order them that way, then take the
front portion. Which sorted option flips the direction, and which slice grabs
the first n?
Tests
- top 3 of unsorted
- empty input
- n larger than len
- n=0
✦ Need help with this task?
Sign in or create a free account to get AI help. Free includes a monthly AI allowance.
warming up
Loading editor…
Consolewaiting
$ Console output will appear here.