Problem Statement
If you are given a string lets call it target
, can you give me back ALL indicies in which target
is found in some input list of strings (this is important, it is a list of strings not numbers), lets call it input_list
. Example inputs:
target = '1234'
input_list = [str(x) for x in range(30000)] + [str(x) for x in range(30000)]
You can not assume that the input_list
is sorted if you want to sort the list you will need to add that to your own version of benchmarkFind()
. The simple solution is to just do the following but this can be very inefficient:
def benchmarkFind(target,input_list):
out = []
for i in range(len(input_list)):
if input_list[i] == target:
out.append(i)
return out
The answer here would be:
idx = [1234, 31234]
Benchmark Results
>>> %timeit benchmarkFind(target,input_list)
100 loops, best of 3: 3.07 ms per loop
User Comment Results
From @trincot and @Abhinav Sood - Slightly better but not great.
def enumerateFind(target,input_list):
return [i for i, e in enumerate(input_list) if e == target]
>>> %timeit enumerateFind(target,input_list)
100 loops, best of 3: 2.96 ms per loop
From @B. M - This looks to be the best answer thus far!
def primitiveFind(target ,input_list):
try :
l=[]
u=-1
while True:
u = input_list.index(target,u+1)
l.append(u)
except ValueError:
return l
>>> %timeit primitiveFind(target,input_list)
1000 loops, best of 3: 577 µs per loop