本帖最后由 lxping 于 2022-12-6 19:08 编辑
你是在for循环的最后将 ch = each 的,循环里面的ch代表的是上一次提前到的each值 , 所以最后一次的each并没有加进去最后的 result 里面,你可以自己试一下将最后的删掉看一下运行结果,当最后的字符重复时,整个重复的字符都会漏掉
- s = input("请输入待压缩字符串:")
- ch = s[0]
- result = ''
- count = 0
- for each in s:
- if each == ch:
- count += 1
- else:
- if count > 2:
- result += ch + str(count)
- if count == 2:
- result += ch + ch
- if count == 1:
- result += ch
- ch = each
- count = 1
- print(f"压缩后的字符串:{result}")
- print(f"压缩率为:{len(result)/len(s)*100:.2f}%")
复制代码- = RESTART: C:/Users/Administrator/Desktop/python/homework/once a week/yszfc.py =
- 请输入待压缩字符串:aaaabbbbbcccccccfg
- 压缩后的字符串:a4b5c7f # g 漏掉了
- 压缩率为:38.89%
- = RESTART: C:/Users/Administrator/Desktop/python/homework/once a week/yszfc.py =
- 请输入待压缩字符串:aaaabbbbbddcccccccee
- 压缩后的字符串:a4b5ddc7 # ee 漏掉了或者说 e2 漏掉了
- 压缩率为:40.00%
复制代码