2015-10-21 75 views
-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] 

这显然是离开。

+0

什么_should_它返回? –

+0

它应该返回一个压缩列表,如:[8,3,4,1,5,3 ...] – Nick

回答

1

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

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)] 
+0

我不熟悉“除了”,“StopIteration”和“尝试”,所以我很难遵循程序 – Nick

+0

'try:except:'允许你处理异常,'next(it)'可以抛出一个异常'StopIteration',如果你传递一个空的迭代。目前你不需要try块,因为在Py3.7之前,一些发生器默默地处理'StopIteration'异常。我将更新代码以删除try块 - 它纯粹是为了将来打样,因为我们只在Py3.5 – AChampion

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 
+1

什么是'start',它似乎没有被使用。它可能需要防范一个空的列表。 – AChampion