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

2024-06-01 04:17:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一些代码来计算每个字符串中有多少对。在

例如:“狗狗”。两个“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") )

Tags: ofto字符串代码inaddreturndef
3条回答

在Python3中使用计数器

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()))

尝试此功能:

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)中的次数。在

^{pr2}$

这应该能做到:

    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

相关问题 更多 >