I try to solve the following problem using Python:
Given a 1-dimensional numeric array arr, find all indices where the value of arr changes. Return for each pair (a, b) (where a != b) an iterator of the indices i where arr[i] == a and arr[i+1] == b.
Example:
If the input array was [1,1,1,1,1,1,5,5,5,5,5,5,5,5,5,5,5,1,1,1,1,1,1,4,4,4,4,4,4,4,4,4,1,1,1,1,1,1], then the function should return the following pairs and iterators:
(1, 5): [6],
(5, 1): [17],
(1, 4): [23],
(4, 1): [32]
If the input is [1,1,1,1,4,4,4,4,1,1,4,4,4,4,4,4,3,3,3,1,4,4,4], then the function should return:
(1, 4): [4, 10, 20],
(4, 1): [8],
(4, 3): [16],
(3, 1): [19]
In my current implementation, for each pair a list is returned, but it may be any iterator. All lists are contained in a dictionary (a defaultdict, to be precise), but they may be returned in any style.
This is my current implementation:
from collections import defaultdict
def find_changepoints(arr):
changepoints = defaultdict(list)
current_value = arr[0]
for (index, value) in enumerate(arr):
if value != current_value:
changepoints[ (current_value, value) ].append(index)
current_value = value
return changepoints