如何计算字符串中的字母对?

时间:2016-11-02 14:15:03

标签: python python-3.x

我想编写计算每个字符串中有多少对的代码。

例如:“狗狗”。彼此相邻有2个“g”,因此代码的输出为1.这是我到目前为止的尝试:

def count_pairs( s ):
 #add in code to count
 cnt= (len(s))  

 #how many pairs of letters exist

 #return the number of letter pairs in each string
 # aadogbbcatcc would return 3
 #aadogcatcc would return 2
 return 0

 print ( count_pairs("ddogccatppig") )
 print ( count_pairs("dogcatpig") )
 print ( count_pairs("xxyyzz") )
 print ( count_pairs("a") )
 print ( count_pairs("abc") )
 print ( count_pairs("aabb") )
 print ( count_pairs("dogcatpigaabbcc") )
 print ( count_pairs("aabbccdogcatpig") )
 print ( count_pairs("dogabbcccatpig") )
 print ( count_pairs("aaaa") )
 print ( count_pairs("AAAAAAAAA") )

3 个答案:

答案 0 :(得分:1)

尝试此功能:

def count_pairs(s):
    pairs_cnt = 0
    unique_chars = set(s)
    for char in unique_chars:
        pairs_cnt += s.count(char + char)
    return pairs_cnt

这将获得字符串中的唯一字符 - set(s) - 并计算每个字符串中成对出现的次数 - s.count(char + char)

>>> count_pairs("ddogccatppig")
3
>>> count_pairs("dogcatpig")
0
>>> count_pairs("xxyyzz")
3
>>> count_pairs("a")
0
>>> count_pairs("abc")
0
>>> count_pairs("aabb")
2
>>> count_pairs("dogcatpigaabbcc")
3
>>> count_pairs("aabbccdogcatpig")
3
>>> count_pairs("dogabbcccatpig")
2
>>> count_pairs("aaaa")
2
>>> count_pairs("AAAAAAAAA")
4

答案 1 :(得分:0)

应该这样做:

    cnt=0
    pair=0
    while (cnt < (len(s)) - 1):
        x = s[cnt]
        y = s[cnt+1]
        if x == y:
            pair += 1
        cnt += 1
    return pair

答案 2 :(得分:0)

在python3中使用Counter

from collections import Counter
def countPairs(word):
    D = Counter(word)
    pairs = 0
    for i in D.keys():
        if D[i] >= 2:
            pairs+=1
    return pairs

print(countPairs(input()))