python文本编码程序

2024-10-02 22:35:24 发布

您现在位置:Python中文网/ 问答频道 /正文

当输入文本到定义运行长度编码器时,代表字母应该被压缩 例如, 输入aaabbac时,输出应为['a','a',3,'b','b',2,'a','c'] 但是我的代码没有压缩。你知道吗

def run_length_encoder(string):
#def compress(string):

    res = []

    count = 1

    #Add in first character
    res.append(string[0])

    #Iterate through loop, skipping last one
    for i in range(len(string)-1):
        if(string[i] == string[i+1]):
            count+=1
            res.append(string[i+1])
        else:
            if(count > 1):
                #Ignore if no repeats
                res.append(count)
            res.append(string[i+1])
            count = 1
    #print last one
    if(count > 1):
        res.append(str(count))
    return res

例如,当输入abbbaa时,输出应该是['a','b','b',4','a','a',2],而我得到的是['a','b','b','b','4','a','a','2']


Tags: in文本stringif定义defcount字母
3条回答

你的逻辑需要修正。固定编辑处理偶数和奇数结束情况。你知道吗

def run_length_encoder(string):
#def compress(string):

    res = []
    count = 1
    if(len(string) == 1):
        res.append(string[0])
        res.append(count)
        return res
    else:
        current = string[0]

        for i in range(1, len(string)):

            if(string[i] == current):
                count+=1
            else:
                res.append(current)
                res.append(count)
                current = string[i]
                count = 1
            i+=1
            if(i == len(string)):
                res.append(current)
                res.append(count)
        return res

在弦上测试: string=“aaabbadddaad”输出:['a',3',b',2',a',2',d',3',a',2',d',1] string=“aaabbaddd”输出:['a',3',b',2',a',2',d',3] string=“aabccdd”输出:['a',2',b',1',c',2',d',2]

你也可以这样做:

def run_length_encoder(str_):
    compressedString = ''
    countConsecutive = 0
    strLen = len(str_)
    for i in range(strLen):
        countConsecutive += 1
        if i + 1 >= strLen or str_[i] != str_[i + 1]:
            compressedString += '' + str_[i] + str(countConsecutive)
            countConsecutive = 0

    return compressedString

sample = 'aaabbac'
result = list(run_length_encoder(sample))
print(result)

Itertools爱你,希望你快乐:

from itertools import chain, groupby

def run_length_encoder(src):
    return list(
        # chain.from_iterable flattens the series of tuples we make inside the
        # loop into a single list.
        chain.from_iterable(
            # groupby returns an iterable (item, group) where group is an
            # iterable that yields a copy of `item` as many times as that item
            # appears consecutively in the input. Therefore, if you take the
            # length of `group`, you get the run length of `item`. This
            # whole expression then returns a series of (letter, count)
            # tuples.
            (letter, len(list(group))) for letter, group in groupby(src)
        )
    )


print(run_length_encoder("aajjjjiiiiohhkkkkkkkkhkkkk"))

相关问题 更多 >