given a list L
, what is the fastest method to find all consecutive length n
subsequences, and find the index of the smallest sum. Here is my (slow) version:
from random import randrange
import numpy as np
L = np.array([randrange(-5000, 5000) for _ in range(10 * 10**6)]) #random array
subarray_length = 3 #for example
sublist_sums = [sum(L[i:i+subarray_length]) for i
in range(0, len(L) - (subarray_length - 1))]
candidate_idx = 0
candidate_sum = sublist_sums[0]
for idx, val in enumerate(sublist_sums[1:]):
if val < candidate_sum:
candidate_sum, candidate_idx = val, idx + 1
print(candidate_idx)
MWE:
L = [6,5,4,3,2,1]
# sublists: [[6,5,4], [5,4,3], [4,3,2], [3,2,1] ]
subarray_length = 3
sublist_sums = [sum(L[i:i+subarray_length]) for i
in range(0, len(L) - (subarray_length - 1))]
# sublist_sums = [15, 12, 9, 6]
for idx, val in enumerate(sublist_sums[1:]):
if val < candidate_sum:
candidate_sum, candidate_idx = val, idx + 1
candidate_idx = 3
# 3 is the index of the first element of the length 3 sublist
# with the smallest sum of all 3 length consecutive sublists