Last active
October 11, 2019 21:51
-
-
Save sergeant-wizard/f2aa07bc939f74cda2aea7955cd9d7fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import timeit | |
import numpy | |
def _encode(msg): | |
# simple but slow | |
ones = numpy.array(msg) == 1 | |
encoded = [] | |
offset = 0 | |
while True: | |
first = numpy.argmax(ones) | |
if not ones[first]: | |
break | |
encoded.append(offset + first) | |
ones = ones[first:] | |
until = numpy.argmin(ones) | |
encoded.append(until) | |
ones = ones[until:] | |
offset += first + until | |
return encoded | |
def encode(msg): | |
length = len(msg) | |
front = numpy.zeros(length + 1) | |
back = numpy.zeros(length + 1) | |
front[:-1] = msg | |
back[1:] = msg | |
ones = numpy.arange(len(front))[(front - back) == 1] | |
zeros = numpy.arange(len(front))[(back - front) == 1] | |
diff = zeros - ones | |
return numpy.stack((ones, diff)).T.flatten().tolist() | |
def test(): | |
pairs = [( | |
[1, 1, 1, 1, 1], | |
[0, 5], | |
), ( | |
[0, 0, 0, 0, 0], | |
[] | |
), ( | |
[0, 0, 1, 1, 1, 0, 0, 1, 1], | |
[2, 3, 7, 2] | |
), ( | |
[0, 0, 1, 1, 1, 0, 0, 1, 1, 0], | |
[2, 3, 7, 2] | |
)] | |
for msg, expected in pairs: | |
assert encode(msg) == expected | |
if __name__ == '__main__': | |
size = 100000 | |
msg = numpy.random.random_integers(0, 1, size) | |
print(timeit.timeit(lambda: encode(msg), number=1000)) | |
print(timeit.timeit(lambda: _encode(msg), number=1000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment