Python Practice › List Programs › Program 98

Decode a run-length encoded list

MediumList Programs · 98 of 100

Write a Python program to decode a run-length encoded list, where [n, x] means x repeated n times.

Advertisement
Input
[[2, 1], 2, 3, [2, 4], 5, 1]
Output
[1, 1, 2, 3, 4, 4, 5, 1]

Approach

  1. Expand [n, x] pairs; copy plain items.

Solution

Python
encoded = [[2, 1], 2, 3, [2, 4], 5, 1]decoded = []for item in encoded:    if isinstance(item, list):        count, value = item        decoded.extend([value] * count)    else:        decoded.append(item)print(decoded)
Output
[1, 1, 2, 3, 4, 4, 5, 1]

Line by line

Lines 5-6

[value] * count repeats the value.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Leave a Comment