如果只有一个字符,如何摆脱计数?

问题描述 投票:0回答:1

在我的程序中,每当我有一个字符时,它的计数就会为 1。例如,如果我有 abbbbbc,我会返回 a1b5c1。我不希望单个字符有计数。我喜欢将程序读为 ab5c。 程序如下:

def rle(character_string):
  compressed_string=""
  count = 1 
  
  for i in range(len(character_string)-1):
    if character_string[i]== character_string[i+1]:  
      count+=1
    else:
     compressed_string += character_string[i] + str(count) 
     count=1
  
  compressed_string += character_string[-1] + str(count) 

  if len(compressed_string) >= len(character_string):
    return character_string
                                
  return compressed_string 


user_string= input("hello user spam character: ")
x=rle(user_string)

print(x)
python string-comparison run-length-encoding
1个回答
0
投票

仅当计数大于 1 时才需要附加计数。

def rle(character_string):
    compressed_string = ""
    count = 1

    for i in range(len(character_string) - 1):
        if character_string[i] == character_string[i + 1]:
            count += 1
        else:
            compressed_string += character_string[i]
            # Append the count only if it's greater than 1
            if count > 1:
                compressed_string += str(count)
            count = 1

    compressed_string += character_string[-1]
    # Same thing for the last character
    if count > 1:
        compressed_string += str(count)

    if len(compressed_string) >= len(character_string):
        return character_string

    return compressed_string

user_string = input("hello user spam character: ")
x = rle(user_string)

print(x)
© www.soinside.com 2019 - 2024. All rights reserved.