python - How can I quickly find the first element in a list that matches a conditional? -
i have 2 subroutines in large program search list first item matches condition , return index. reason, these take large percentage of program's execution time, , wondering how optimize them.
def next_unignored(start_index, ignore, length): """takes start index, set of indices ignore, , length of list , finds first index not in set ignore.""" in xrange(start_index+1, length): if not in ignore: return def last_unignored(start_index, ignore, lower_limit): """the same other, backwards.""" in xrange(start_index-1, lower_limit-1, -1): if not in ignore: return
does have tips on optimizing these routines or others follow similar pattern?
example input:
from sample import next_unignored, last_unignored start_index = 0 ignore = set([0,1,2,3,5,6,8]) length = 100 print next_unignored(start_index, ignore, length) # => 4 start_index = 8 ignore = set([0,1,2,3,5,6,8]) lower_limit = 0 print last_unignored(start_index, ignore, lower_limit) # => 7
>>> import numpy np >>> start,length = 0,100 >>> ignore = set([0,1,2,3,5,6,8]) >>> x = np.arange(start,start+length) >>> x[~np.in1d(x,ignore)][0] 4
without numpy
>>> start,length = 0,100 >>> ignore = set([0,1,2,3,5,6,8]) >>> my_list = set(range(start,start+length)) >>> my_list2 = my_list - ignore >>> >>> print max(my_list2) # highest number not in ignore list 99 >>> print min(my_list2) #lowest value not in ignore list 4
if ignore set sparse method may faster since short circuits if ignore set dense should speed considerably
Comments
Post a Comment