简体   繁体   English

我如何计算不规则重复字符的数量?

[英]How can i get count of irregular repeating characters?

Input is xyz = 'aaabbbaaa' , I want output as 3a3b3a输入是xyz = 'aaabbbaaa' ,我想要 output 作为3a3b3a

xyz = 'aaabbbaaa'
p = xyz[0]
i = 0
out = {}
while i < len(xyz):
    if p == xyz[i]:
        if xyz[i] not in out:
            out[xyz[i]] = []
        out[xyz[i]].append(xyz[i])
    else:
        p = xyz[i]
    i += 1
print(out)

Help me, How can i achieve this??帮帮我,我怎样才能做到这一点?

This is likely the simplest method and easiest to understand.这可能是最简单且最容易理解的方法。

Create a tally variable and increment it when you see repeating characters, then when you see a non repeating character write the previous character and the tally to a string and start the tally back to 1.... repeat until string ends创建一个记tally变量并在看到重复字符时递增它,然后当您看到一个非重复字符时将前一个字符和记数写入一个字符串并从 1 开始记数……重复直到字符串结束

xyz = 'aaabbbaaa'
tally = 1
string = ''
prev = xyz[0]
for char in xyz[1:]:
    if char == prev:
        tally += 1
    else:
        string += str(tally) + prev
        prev = char
        tally = 1
string += str(tally) + prev
print(string)   # 3a3b3a

what result do you expect to get if the string has single characters?如果字符串只有单个字符,您希望得到什么结果? suppose we should just skip a single character:假设我们应该跳过一个字符:

from re import sub

s = 'aabbbcaaabc'
sub(r'(\w)\1*',lambda m: f"{l if (l:=len(m[0]))>1 else ''}{m[1]}",s)

>>>
# '2a3bc3abc'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM