Python统计字符串子串重复次数

2025-11-10 21:54:49

1、遍历字符串所有子串,并存于字典中,每一个子串,在字典中寻找,如果存在,key加一,否则新加入key,赋值为1。

dic={}

s='AAAA'

for i in range(len(s)):

    for j in range(i+2,len(s)):

        t=s[i:j]

    if  t in dic:

        dic[t]+=1

    else:

        dic[t]=1

Python统计字符串子串重复次数

2

Python统计字符串子串重复次数

Python统计字符串子串重复次数

3、这个方法我把它叫做蠕虫。因为他是无重复统计,类似于蠕虫的运动。

获取所有字符,并统计在字符串中出现的次数。

def worm(s):

    dic={}

    for i in range(len(s)-3):

        j=i

        s1=s[i:i+2]

        s2=s[i+2:]

        while s2.find(s1)!=-1:

            count=1

            stemp=s2

            while stemp.find(s1)!=-1:             

                count+=1

                stemp=stemp[stemp.find(s1)+len(s1):]       

            if not(s1 in dic):

                dic[s1]=count

            j+=1

            s1=s[i:j+2]

            s2=s[j+2:]

    return dic

4、这是一个升级版的方法,因为它在比较之前引入了查询,避免不必要的统计

希望各位生物信息工作者可以相互交流,提出修改建议。

def worm(s):

    dic={}

    for i in range(len(s)-3):

        j=i

        s1=s[i:i+2]

        if s1 in dic:

            continue

        s2=s[i+2:]

        while s2.find(s1)!=-1:

            count=1

            stemp=s2

            while stemp.find(s1)!=-1:             

                count+=1

                stemp=stemp[stemp.find(s1)+len(s1):]       

            if not(s1 in dic):

                dic[s1]=count

            j+=1

            s1=s[i:j+2]

            s2=s[j+2:]

    return dic

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢