from collections import deque def farthest_reachable(A, L): if A != sorted(A): raise ValueError("A is not sorted") if L <= 0: raise ValueError("L is not positive") n = len(A) Q = deque([A[0]]) # a double-ended queue containing A[0] B = [] i = 1 while i < n or len(Q) > 0: print("{0:2d}".format(i), B, list(Q)) if i < n and (len(Q) == 0 or A[i] <= Q[0] + L): Q.append(A[i]) # add A[i] to the right of the deque i = i + 1 else: B.append(Q[-1]) # append to B the rightmost elt in Q Q.popleft() # remove the leftmost elt from Q print("{0:2d}".format(i), B, list(Q)) return B if __name__ == "__main__": print("Result:", farthest_reachable([1.0, 1.5, 2.1, 2.6, 2.9, 3.0, 4.2, 5.0, 5.2, 6.3, 7.0, 8.0, 8.5, 9.1, 9.6, 9.9, 10.0], 0.1)) print("Result:", farthest_reachable([1.0, 1.5, 2.1, 2.6, 2.9, 3.0, 4.2, 5.0, 5.2, 6.3, 7.0, 8.0, 8.5, 9.1, 9.6, 9.9, 10.0], 3))