You can go one step further and create a
primes_in_range
function that does the dropping for you. This might actually become a bottleneck at some point, (if a is large and a >> b - a), but at that point you only need to change the implementation of one function.Your
reference_slice
is always the same length, but if you want to add the next element you need to resort to list slicing and list addition, both of which might create a copy. Instead, you can usecollections.deque
with the optional argumentmaxlen
. If you append another element, the first one will be automatically pushed out.Similarly, you can avoid the slice in the calculation of the differences by just including the first element. You just have to add a
0
as first element in the correct differences list. Alternatively you could just define adiff
function and adjust the correct differences to be relative to the previous elements instead of the first.You should limit your
try
block as much as possible. This increases readability on one hand, and reduces unwanted exceptions being caught on the other (not such a big risk here, but true in general).But even better is to not need it at all. A
for
loop consumes all elements of an iterable, which is exactly what we need here. This way we don't even need to special case the first five elements, because if the list is too short, the pattern cannot match. Alternatively, you could implement awindowed(it, n)
function, which is what I have done below.You should try to avoid magical values. In your code there are two. The first is the length of the pattern and the second is the pattern itself. Fortunately, the former is already given by the latter. I would make the pattern an argument of the function, which makes it also more general. At this point a less generic name might also be needed (although the name I propose below is maybe not ideal either).
You should protect the code executing your functions with a
if __name__ == "__main__";
guard to allow importing from this script without it being run.