如何计算字符串中找到的三胞胎数?

2024-10-02 08:29:57 发布

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

string1=“abbbcccd” string2=“abbbdccc”

如何查找字符串中找到的三胞胎数。三元组表示一行中出现3次的字符。三元组也可以重叠,例如在字符串2中(abbbdccc)

输出应为:

2 < -- string 1
3 <-- string 2

我是python和stack overflow的新手,所以如果您在写作过程中有任何疑问,我们将不胜感激


Tags: 字符串stringstack过程字符三元组新手string1
2条回答

尝试使用while循环遍历字符串,并比较该字符和该字符前面的其他两个字符是否相同。这也适用于重叠

string1 = "abbbcccd"
string2 = "abbbbdccc"
string3 = "abbbbddddddccc"

def triplet_count(string):
    it = 0    # iterator of string
    cnt = 0   # count of number of triplets
    while it < len(string) - 2:
        if string[it] == string[it + 1] == string[it + 2]:
            cnt += 1
        it += 1
    return cnt

print(triplet_count(string1)) # returns 2
print(triplet_count(string2)) # returns 3
print(triplet_count(string3)) # returns 7

这个简单的脚本应该可以工作

my_string = "aaabbcccddddd"

# Some required variables
old_char = None
two_in_a_row = False
triplet_count = 0

# Iterates through characters of a given string
for char in my_string:
    # Checks if previous character matches current character
    if old_char == char:
        # Checks if there already has been two in a row (and hence now a triplet)
        if two_in_a_row:
            triplet_count += 1
        two_in_a_row = True
    # Resets the two_in_a_row boolean variable if there's a non-match.
    else:
        two_in_a_row = False
    old_char = char

print(triplet_count) # prints 5 for the example my_string I've given

相关问题 更多 >

    热门问题