3 回答
TA贡献1808条经验 获得超4个赞
你可以让它更简单并在最后添加一个字符:
def compress(string):
output = ""
counter = 0
string = string + '|'
for element in range(0, len(string)):
# if statement checking if current character was last character
if string[element] == string[element - 1]:
# if it was, then the character has been written more than one
# time in a row, so increase counter
counter = counter + 1
elif element != len(string):
output = output + string[element - 1] + str(counter)
counter = 1
return output[2:]
data = "aaaabbbchhtttttttf"
print(data)
compressedData = compress(data)
print(compressedData)
TA贡献1796条经验 获得超10个赞
def compress(string):
output = ""
counter = 1
for element in range(1, len(string)):
# if statement checking if current character was last character
if string[element] == string[element - 1]:
# if it was, then the character has been written more than one
# time in a row, so increase counter
counter = counter + 1
else:
# when we detect a new character reset the counter
# and also record the character and how many times it was repeated
output = output + string[element - 1] + str(counter)
counter = 1
return output + string[-1] + str(counter)
另外请注意,你需要开始计数形式1不0和摆脱firstLoop
添加回答
举报