kinda new to python, and I'm having trouble coming up with a solution to this problem.
Suppose I have a list A and suppose I want to return a list B containing at least the three smallest values, including repeated values. How would I write the logic for this? I'm at a bit of a loss as to how to translate this thought into code.
Example:
A = [1,2,3,4,4]
b = [1,2,3]
A = [1,2,3,3,4]
B = [1,2,3,3]
A = [1,1,2,2,3]
B = [1,1,2,2]
A = [1,1,2,3]
B = [1,1,2]
You can use the heapq
module:
import heapq
def nsmallestwithrepeats(A, n=3):
b = heapq.nsmallest(n, A)
try:
b = set(b)
except TypeError:
pass
return [a for a in A if a in b]
for A in [1,2,3,4,4], [1,2,3,3,4], [1,1,2,2,3], [1,1,2,3]:
print(nsmallestwithrepeats(A))
Output:
[1, 2, 3]
[1, 2, 3, 3]
[1, 1, 2, 2]
[1, 1, 2]
As @Mathieu Borderé points out instead of forming a set it is probably more efficient to simply compare to the largest element of b:
def nsmallestwithrepeats(A, n=3):
b = heapq.nsmallest(n, A)
return [a for a in A if a <= b[-1]]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments