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

 时间:2026-02-12 07:50:46

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

  • 团油如何开启车牌支付?
  • 过年该回哪个家?婆家还是娘家?
  • 红豆小米糕怎么做简单又好吃?
  • 孕晚期喝玉米须水有什么作用
  • 叉烧包的做法
  • 热门搜索
    噗是什么意思 梦见驴是什么意思 梦见开车是什么意思 mine是什么意思 制动是什么意思 什么风什么雨 8月26日是什么星座 庆余年第二季什么时候上映 1月31日是什么星座 什么是数字货币