在Python中创建压缩函数?

2024-06-06 17:05:53 发布

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

我需要创建一个名为compress的函数,它通过用字母和数字替换任何重复的字母来压缩字符串。我的函数应该返回字符串的缩短版本。我已经数到了第一个字符,但没有其他字符。

例如:

>>> compress("ddaaaff")
'd2a3f2'


 def compress(s):
     count=0

     for i in range(0,len(s)):
         if s[i] == s[i-1]:
             count += 1
         c = s.count(s[i])

     return str(s[i]) + str(c)

Tags: 函数字符串in版本fordefcount字母
3条回答

带发电机的短型:

from itertools import groupby
def compress(string):
    return ''.join('%s%s' % (char, sum(1 for _ in group)) for char, group in groupby(string)).replace('1', '')

(1)用groupby(string)按字符分组

(2)用sum(1 for _ in group)计数组的长度(因为组上不可能有len

(3)加入适当的格式

(4)去除单个项目的1字符

这不起作用有几个原因。你真的需要先自己调试一下。输入一些print语句来跟踪执行过程。例如:

def compress(s):
    count=0

    for i in range(0, len(s)):
        print "Checking character", i, s[i]
        if s[i] == s[i-1]:
            count += 1
        c = s.count(s[i])
        print "Found", s[i], c, "times"

    return str(s[i]) + str(c)

print compress("ddaaaff")

输出如下:

Checking character 0 d
Found d 2 times
Checking character 1 d
Found d 2 times
Checking character 2 a
Found a 3 times
Checking character 3 a
Found a 3 times
Checking character 4 a
Found a 3 times
Checking character 5 f
Found f 2 times
Checking character 6 f
Found f 2 times
f2

Process finished with exit code 0

(1)你把除了最后一封信以外的所有搜索结果都扔掉了。 (2) 你计算所有的事件,而不仅仅是连续的。 (3) 你把一个字符串转换成一个字符串——多余的。

试着用铅笔和纸来完成这个例子。写下你作为一个人用来解析字符串的步骤。把它们翻译成Python。

下面是压缩函数的简短python实现:

def compress(string):

    res = ""

    count = 1

    #Add in first character
    res += string[0]

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

下面是几个例子:

>>> compress("ddaaaff")
'd2a3f2'
>>> compress("daaaafffyy")
'da4f3y2'
>>> compress("mississippi")
'mis2is2ip2i'

相关问题 更多 >