a = [3, 4, 2, 1, 7, 6, 5]
b = [4, 6]
The answer should be 1. Because in a, 4 appears first in list b, and it's index is 1.
The question is that is there any fast code in python to achieve this?
PS: Actually a is a random permutation and b is a subset of a, but it's represented as a list.
If b
is to be seen as a subset (order doesn't matter, all values are present in a
), then use min()
with a map()
:
min(map(a.index, b))
This returns the lowest index. This is a O(NK) solution (where N is the length of a
, K that of b
), but all looping is executed in C code.
Another option is to convert a
to a set and use next()
on a loop over enumerate()
:
bset = set(b)
next(i for i, v in enumerate(a) if v in bset)
This is a O(N) solution, but has higher constant cost (Python bytecode to execute). It heavily depends on the sizes of a
and b
which one is going to be faster.
For the small input example in the question, min(map(...))
wins:
In [86]: a = [3, 4, 2, 1, 7, 6, 5]...: b = [4, 6]...:In [87]: %timeit min(map(a.index, b))...:
608 ns ± 64.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)In [88]: bset = set(b)...:In [89]: %timeit next(i for i, v in enumerate(a) if v in bset)...:
717 ns ± 30.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)