I have a big list, which may carry thousands to millions of entries. I set a window of finite size to slide over the list. I need to count the matched elements in the windows and repeat the procedure by sliding the window 1 position forward at a time. Here is a simple example of a list
L = [1 2 1 3 4 5 1 2 1 2 2 2 3 ]
Assuming the window is of the length of 3, it will capture
- [1 2 1] which contains one pair of matching elements (1 & 1)
- move the windows forward by 1 position => [2 1 3], no matching elements
- move the windows forward by 1 position => [1 3 4], no matching elements
- move the windows forward by 1 position => [3 4 5], no matching elements
- move the windows forward by 1 position => [4 5 1], no matching elements
- move the windows forward by 1 position => [5 1 2], no matching elements
- move the windows forward by 1 position => [1 2 1], 1 matching elements (1 & 1)
- move the windows forward by 1 position => [2 1 2], 1 matching elements (2 & 2)
- move the windows forward by 1 position => [1 2 2], 1 matching elements (2 & 2)
- move the windows forward by 1 position => [2 2 2], 3 matching elements ([2 2 -], [2 - 2], [- 2 2])
- move the windows forward by 1 position => [2 2 3], 1 matching elements (2 & 2)
So total 1 + 1 + 1 + 1 + 3 + 1 = 8 matching pairs. I found the idea to use itertools to find the combination of all elements in a window and develop a code to find all the matching pairs
import itertools
L = [1,2,1,3,4,5,1,2,1,2,2,2,3]
winlen = 3
totalMatch = 0
for n in range(len(L)-winlen+1):
window = [L[n+i] for i in range(winlen)]
A = list(itertools.combinations(window, 2))
match = [a==b for a, b in A]
totalMatch += sum(match)
it works for a short list but for the list and the windows getting large, this code is so slow. I have been working with C++ for years and decide to switch to python, I will appreciate it if there is any hint to improve the efficiency of the code.