-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.py
21 lines (16 loc) · 943 Bytes
/
solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Your task is to write a function that does just what the title suggests
# (so, fair warning, be aware that you are not getting out of it just throwing a lame bas sorting method there)
# with an array/list/vector of integers and the expected number n of smallest elements to return.
# Also:
# the number of elements to be returned cannot be higher than the array/list/vector length;
# elements can be duplicated;
# in case of duplicates, just return them according to the original order (see third example for more clarity).
# Same examples and more in the test cases:
# first_n_smallest([1,2,3,4,5],3) == [1,2,3]
# first_n_smallest([5,4,3,2,1],3) == [3,2,1]
# first_n_smallest([1,2,3,4,1],3) == [1,2,1]
# first_n_smallest([1,2,3,-4,0],3) == [1,-4,0]
# first_n_smallest([1,2,3,4,5],0) == []
def first_n_smallest(arr, n):
arr = sorted(enumerate(arr), key=lambda x: x[1])[:n]
return [i[1] for i in sorted(arr, key=lambda x: x[0])]