Skip to content

Instantly share code, notes, and snippets.

@itdaniher
Last active October 23, 2021 11:26
Show Gist options
  • Save itdaniher/3f57be9f95fce8daaa5a56e44dd13de5 to your computer and use it in GitHub Desktop.
Save itdaniher/3f57be9f95fce8daaa5a56e44dd13de5 to your computer and use it in GitHub Desktop.
Run Length Encoding, Two Ways
import numpy as np
import itertools
def rle(x):
where = np.flatnonzero
x = np.asarray(x)
n = len(x)
if n == 0:
return np.array([], dtype=int)
starts = np.r_[0, where(~np.isclose(x[1:], x[:-1], equal_nan=True)) + 1]
lengths = np.diff(np.r_[starts, n])
values = x[starts]
return np.dstack((lengths, values))[0]
def rld(runs):
runs_t = np.transpose(runs)
lengths = runs_t[0].astype(int)
values = runs_t[1].astype(int)
starts = np.concatenate(([0],np.cumsum(lengths)[:-1]))
starts, lengths, values = map(np.asarray, (starts, lengths, values))
ends = starts + lengths
n = ends[-1]
x = np.full(n, 0)
for lo, hi, val in zip(starts, ends, values):
x[lo:hi] = val
return x
ilen = lambda it: sum(1 for _ in it)
rle = lambda xs: ((ilen(gp), x) for x, gp in itertools.groupby(xs))
rld = lambda xs: itertools.chain.from_iterable(itertools.repeat(x, n) for n, x in xs)
@itdaniher
Copy link
Author

the fancy numpy rt is slightly faster...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment