Mercurial > louis > peeves
view arrays/rle/solution.py @ 0:20fea762903e
Import some exercises and solutions
author | Louis Opter <kalessin@kalessin.fr> |
---|---|
date | Sat, 29 Jun 2013 19:30:31 -0700 |
parents | |
children |
line wrap: on
line source
#!/usr/bin/env python def rle_8b(buf): acc = 1 ret = [] n = len(buf) i = 1 while i < n: if buf[i] != buf[i - 1]: ret.append((acc, buf[i - 1])) acc = 1 if buf[i] == buf[i - 1]: if acc == 2**8 - 1: # NOTE: the rationale for doing that is to later decode the # file (it's easier if you know on how many bits the length is # encoded). You don't have to dot it. ret.append((acc, buf[i])) acc = 1 else: acc += 1 i += 1 ret.append((acc, buf[i - 1])) return ret buf1 = "fjesffffffflllllljf" buf2 = "fehs1111233" buf3 = 256 * "a" + 512 * "C" print("rle_8b({0}) → {1}".format(buf1, rle_8b(buf1))) print("rle_8b({0}) → {1}".format(buf2, rle_8b(buf2))) print("rle_8b({0}) → {1}".format(buf3, rle_8b(buf3)))