I have a sorted list (without duplicates) in python, like so,
l = [1, 3, 5, 8, 9, 11, 13, 17]
I would like a take a slice of this based on the list values. So if the value of interest is say, 5. Then I want to locate this value in the list and get 3 values before it in the list.
I can get to my objective with the following function
def f(k):
if k in l:
i = l.index(k)
return (l[i-2:i+1])
else:
pass
print (f(5))
[1, 3, 5]
print (f(13))
[9, 11, 13]
However, I have two problems. I do not know what I should do if the value of interest is not a list member. f(6) should also return [1,3,5]. I don't know how to locate 6 in this list
Is there some 'pythonic' way to do this
you can use:
less_values = [x for x in l if x < 5]
this should you give an new list with all values smaller than 5
and there you can easily select the last 3 values
I'll take a stab that since the list is sorted, and without duplicates, then you're supposed to be using some form of binary search. Python conveniently has a bisect
module as part of the standard library.
Code:
import bisect
data = [1, 3, 5, 6, 8, 9, 11, 13, 17]
for val in range(19):
pos = bisect.bisect_right(data, val)
print val, '->', data[max(0, pos-3):pos]
Output:
0 -> []
1 -> [1]
2 -> [1]
3 -> [1, 3]
4 -> [1, 3]
5 -> [1, 3, 5]
6 -> [3, 5, 6]
7 -> [3, 5, 6]
8 -> [5, 6, 8]
9 -> [6, 8, 9]
10 -> [6, 8, 9]
11 -> [8, 9, 11]
12 -> [8, 9, 11]
13 -> [9, 11, 13]
14 -> [9, 11, 13]
15 -> [9, 11, 13]
16 -> [9, 11, 13]
17 -> [11, 13, 17]
18 -> [11, 13, 17]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With