运行长度编码功能(无库或对象方法)

时间:2015-10-21 04:09:12

标签: python function python-3.x compression run-length-encoding

我需要编写一个使用行程编码来压缩列表的程序。我不知道怎么做,经过一段时间改变我的程序,我甚至不知道它现在在做什么。

我们不允许导入和库或使用python字符串或列表对象方法(如append())。

这就是我现在所处的位置:

def rle(x):
    c_list = []
    count = 0 
    for num in x: 
        if x[num] == x[num - 1]:
            c+=[x[num], count]
            count+= 1
     # ...
     return c

使用此列表作为示例:

[8,8,8,4,5,5,5,6,6,6,6,9,8,1,1,1,1,3,3]

它会返回:

[6, 0, 6, 1, 6, 2, 5, 3, 5, 4, 5, 5, 5, 6, 
5, 7, 5, 8, 5, 9, 6, 10, 6, 11, 8, 12, 8,
13, 8, 14, 8, 15] 

这显然是偏离了。

2 个答案:

答案 0 :(得分:1)

应该是什么编码?假设OperationContract的元组,那么你可以实现一个生成器:

(element, count)

答案 1 :(得分:0)

def rle(x):
    prev = x[0]
    count = 0
    for item in x:
        if item == prev:
            count += 1
        else:
            yield prev, count
            prev = item
            count = 1
    yield prev, count

x = [8,8,8,4,5,5,5,6,6,6,6,9,8,1,1,1,1,3,3] 
print list(rle(x))

打印

[(8, 3), (4, 1), (5, 3), (6, 4), (9, 1), (8, 1), (1, 4), (3, 2)]

如果您需要

[8, 3, 4, 1, 5, 3, 6, 4, 9, 1, 8, 1, 1, 4, 3, 2]

只需将每个yield替换为2 yields

yield prev
yield count
相关问题