-1

我需要编写一个使用运行长度编码来压缩列表的程序。我不知道该怎么做,在一次改变我的程序之后,我什至不知道它现在在做什么。

我们不允许导入和库或使用 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] 

这显然是遥不可及的。

4

2 回答 2

1

编码应该是什么?假设元组(element, count)then 你可以实现一个生成器:

def rle(iterable):
    it = iter(iterable)
    e, c = next(it), 1       # StopIteration silently handled before Py3.7
    for n in it:
        if n == e:
            c += 1
            continue
        yield (e, c)         # "yield from (e, c)" if you need a flat list
        e, c = n, 1
    yield (e, c)

>>> list(rle('aaaaaddddffgghjjjjj'))
[('a', 5), ('d', 4), ('f', 2), ('g', 2), ('h', 1), ('j', 5)]
>>> list(rle([8,8,8,4,5,5,5,6,6,6,6,9,8,1,1,1,1,3,3]))
[(8, 3), (4, 1), (5, 3), (6, 4), (9, 1), (8, 1), (1, 4), (3, 2)]
于 2015-10-21T04:24:20.623 回答
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为 2yields

yield prev
yield count
于 2015-10-21T04:26:13.250 回答