>>> 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)
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', '')
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
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
带发电机的短型:
(1)用
groupby(string)
按字符分组(2)用
sum(1 for _ in group)
计数组的长度(因为组上不可能有len
)(3)加入适当的格式
(4)去除单个项目的
1
字符这不起作用有几个原因。你真的需要先自己调试一下。输入一些print语句来跟踪执行过程。例如:
输出如下:
(1)你把除了最后一封信以外的所有搜索结果都扔掉了。 (2) 你计算所有的事件,而不仅仅是连续的。 (3) 你把一个字符串转换成一个字符串——多余的。
试着用铅笔和纸来完成这个例子。写下你作为一个人用来解析字符串的步骤。把它们翻译成Python。
下面是压缩函数的简短python实现:
下面是几个例子:
相关问题 更多 >
编程相关推荐