Here is one way to do it using a generator:
def compress(signal):
prev_t, prev_val = None, None
for t, val in zip(*signal):
if val != prev_val:
if prev_t is not None:
yield prev_t, prev_val
yield t, val
prev_t, prev_val = None, val
else:
prev_t, prev_val = t, val
if prev_t is not None:
yield prev_t, prev_val
signal = [
[0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1], #time values
[1,1,1,2,3,4,4,4,4,2,1,1] #function values
]
print zip(*compress(signal))
I think it would be more natural to transpose signal
, storing it like so:
[(0.0, 1),
(0.1, 1),
(0.2, 1),
(0.3, 2),
(0.4, 3),
(0.5, 4),
(0.6, 4),
(0.7, 4),
(0.8, 4),
(0.9, 2),
(1.0, 1),
(1.1, 1)]
This way the two zip(*seq)
calls would be unnecessary and the entire processing can be done on the fly.
Finally, if this is still too slow for large input, it might be worth looking into using NumPy. Here is an outline of one such solution:
import numpy as np
signal = [
[0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1], #time values
[1,1,1,2,3,4,4,4,4,2,1,1] #function values
]
def npcompress(signal):
sig=np.array(signal)
idx = np.where(sig[1][1:] != sig[1][:-1])[0]
idx_arr = np.sort(np.array(list(set(idx) | set(idx + 1) | set([0]) | set([len(sig[1]) - 1]))))
return sig.T[idx_arr]
print npcompress(signal).T