-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathtop.py
More file actions
33 lines (26 loc) · 747 Bytes
/
top.py
File metadata and controls
33 lines (26 loc) · 747 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
"""
``top(it, n)`` returns the "greatest" ``n`` elements of the iterable ``t``.
Example:
# tag::TOP_DOCTEST[]
>>> top([4, 1, 5, 2, 6, 7, 3], 3)
[7, 6, 5]
>>> l = 'mango pear apple kiwi banana'.split()
>>> top(l, 3)
['pear', 'mango', 'kiwi']
>>>
>>> l2 = [(len(s), s) for s in l]
>>> l2
[(5, 'mango'), (4, 'pear'), (5, 'apple'), (4, 'kiwi'), (6, 'banana')]
>>> top(l2, 3)
[(6, 'banana'), (5, 'mango'), (5, 'apple')]
# end::TOP_DOCTEST[]
"""
# tag::TOP[]
from collections.abc import Iterable
from typing import TypeVar
from comparable import SupportsLessThan
LT = TypeVar('LT', bound=SupportsLessThan)
def top(series: Iterable[LT], length: int) -> list[LT]:
ordered = sorted(series, reverse=True)
return ordered[:length]
# end::TOP[]