Getting A Boundary Of An Item From Another List
I have a list which is like, tlist = [0.0, 0.07, 0.13, 0.15, 0.2, 0.22] (which is sorted) I have another list which is, newlist = [0.0, 0.04, 0.08, 0.12, 0.16, 0.2] (numbers with
Solution 1:
Simple approach using enumerate
:
for n in newlist:
for i, t in enumerate(tlist):
if t > n:
# found upper boundry, previous must be equal orlowerupper, lower = t, tlist[i-1]
breakprintlower, n, upper
Solution 2:
Using the code you posted from your question Unexpected output from Newton's method, here a time
function which correctly matches the boundary:
deftime() :
t_u = 0
i = 0while i < len(tlist) - 1:
# if the number is in the range# do the calculations and move to the next numberif t_u > tlist[i] and t_u < tlist[i + 1] :
print"\n The t_u value:", t_u, 'is between',
print"start:", tlist[i], " and end: ", tlist[i+1]
poly = poly_coeff(tlist[i], tlist[i + 1], t_u)
Newton(poly)
t_u = t_u + 0.04# regular time interval# if the number is at the boundary of the range# go to the next number without doing the calculationelif t_u == tlist[i] or t_u == tlist[i + 1] :
print"\n The t_u value:", t_u, 'is on the boundary of',
print"start:", tlist[i], " and end: ", tlist[i+1]
t_u = t_u + 0.04# regular time interval# if the number isn't in the range, move to the next rangeelse :
i += 1
Solution 3:
>>>tlist = [0.0, 0.07, 0.13, 0.15, 0.2, 0.22]>>>newlist = [0.0, 0.04, 0.08, 0.12, 0.16, 0.2]>>>defgetrange(x):...for i inrange(len(tlist)):...if tlist[i] > x:...return tlist[max(0, i-1)], tlist[i]>>>[getrange(x) for x in newlist]
8: [(0.0, 0.07),
(0.0, 0.07),
(0.07, 0.13),
(0.07, 0.13),
(0.15, 0.2),
(0.2, 0.22)]
Does this help?
Solution 4:
Somewhat plain and assuming tlist
is sorted
def find_interval(tlist, item):
forlower, upperin zip(tlist[:-1], tlist[1:]):
iflower <= item < upper:
return (lower, upper)
return None # Or raise some "IntervalNotFoudException"print((find_interval(tlist, item) for item in newlist))
Edit : Made it shorter using zip
Solution 5:
You can use the bisect module for this:
import bisect
defbisect_range(sortedlist, tofind):
for t in tofind:
loc = bisect.bisect_right(sortedlist, t)
yield (sortedlist[loc-1], sortedlist[loc])
tlist = [0.0, 0.07, 0.13, 0.15, 0.2, 0.22]
newlist = [0.0, 0.04, 0.08, 0.12, 0.16, 0.2]
printlist(bisect_range(sorted(tlist), newlist))
This is O(N * log(M)) where M is the length of the sorted list and N is the length of the items being searched, because the bisect_right
function is O(log(M)) and we are calling it once for each item in the search list of length N. Sorting the initial list (if it's not already sorted) is O(M * log(M)).
Post a Comment for "Getting A Boundary Of An Item From Another List"