首页 > 解决方案 > 计算子字符串中的元音和辅音

问题描述

在查找和计算所有可能以元音或辅音开头的子串时遇到一些麻烦,并在输出中打印它们的数量,一些想法?

word = input() 

# defining vowels
vowels = "aeiou"

count_v = 0
count_c = 0

word.lower()

for i in range(len(word)):
    for j in range(i, len(word)):
        for k in range(i, (j + 1)):
            print(word[k], end="")
        print()

print(f"number of substrings starting with Vowels: {count_v} - number of substrings starting with Consonants: {count_c} ```

标签: python

解决方案


用于enumerate()将字母和索引放在一起,而不是使用range(len(word)).

您不需要嵌套循环,因为从特定索引开始的所有子字符串都以相同的字母开头。从特定索引开始,有len(word) - index子字符串。

如果字母不是元音,您应该检查它是否是字母,以确定它是否是辅音,以防用户输入不是字母的字符。

for i, letter in enumerate(word.lower()):
    if letter in vowels:
        count_v += len(word) - i
    elif letter.isalpha():
        count_c += len(word) - i

推荐阅读