Home > Blockchain >  How to create an Run Length decoder in python?
How to create an Run Length decoder in python?

Time:10-17

I need the decoder to take input like

[3, 15, 6, 4]

and output

[15, 15, 15, 4, 4, 4, 4, 4, 4]

I already have an encoder that works perfectly, but I am unsure how I would go about reversing the process.

CodePudding user response:

You can use list comprehension:

lst = [3, 15, 6, 4]

output = [x for n, x in zip(lst[::2], lst[1::2]) for _ in range(n)]
print(output) # [15, 15, 15, 4, 4, 4, 4, 4, 4]

CodePudding user response:

One solution can be to use a nested list comprehension (i.e. equivalent to two for loops), iterating over the even indices of the list L:

>>> L = [3, 15, 6, 4]
>>> [e for i in range(0, len(L), 2) for e in L[i] * [L[i   1]]]
[15, 15, 15, 4, 4, 4, 4, 4, 4]

A way of achieving the same, using a single for loop and list.extend:

>>> L = [3, 15, 6, 4]
>>> result = []
>>> for i in range(0, len(L), 2):
...   result.extend(L[i] * [L[i   1]])
...
>>> result
[15, 15, 15, 4, 4, 4, 4, 4, 4]

CodePudding user response:

@j1-lee's answer works but creates temporary lists that may be an issue if space efficiency is a concern.

You can create an iterator over the input list instead to iterate through the list in a space-efficient manner:

lst = [3, 15, 6, 4]
seq = iter(lst)
print([i for n, i in zip(seq, seq) for _ in range(n)])

This outputs:

[15, 15, 15, 4, 4, 4, 4, 4, 4]

CodePudding user response:

There are lots of ways to do this. One is list multiplication and summation:

sum((lst[n] * lst[n   1:n   2] for n in range(0, len(lst), 2)), start=[])

You can also use itertools.chain.from_iterable instead of sum:

list(chain.from_iterable(lst[n] * lst[n   1:n   2] for n in range(0, len(lst), 2)))

You can also use itertools.repeat to evaluate the expansion even more lazily:

list(chain.from_iterable(repeat(lst[n   1], lst[n]) for n in range(0, len(lst), 2)))

If you're willing to use numpy, you can do

np.repeat(lst[1::2], lst[::2])
  • Related