python - 计算子字符串中的元音和辅音
问题描述
在查找和计算所有可能以元音或辅音开头的子串时遇到一些麻烦,并在输出中打印它们的数量,一些想法?
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} ```
解决方案
用于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
推荐阅读
- tinymce - TinyMCE:删除 ../ 按图片链接
- php - 从此查询创建视图
- sql - 将 sql 项转换为 cake php
- c++ - 初始化时定义的具有不同行为的 C++ 成员函数
- r - 如何修复我的 geom_text 标签,使其适合我的柱形图的条形?
- r - 为什么 Shiny-app 对用户输入没有反应
- laravel - Laravel 签名 URL 中间件
- javascript - 使用 JavaScript 或 jQuery 按值获取字段集的输入
- azure - 使用基础软件部署 Azure VM、ARM 模板
- ruby-on-rails-4 - 如何测试使用 rspec 调用的私有方法