Python程序使用set在给定的字符串中计算元音的数量
在这个程序中,给定了一个用户输入的字符串。我们必须计算这个字符串中元音的数量。这里我们使用Python中的set。Set是一种无序的集合数据类型,可迭代、可变且没有重复元素。
示例
Input : str1=pythonprogram Output : 3
算法
Step 1: First we use one counter variable which is used to count the vowels in the string. Step 2: Creating a set of vowels. Step 3: Then traverse every alphabet in the given string. Step 4: If the alphabet is present in the vowel set then counter incremented by 1. Step 5: After the completion of traversing print counter variable.
示例代码
#计算元音的程序
#使用set的字符串
def countvowel(str1):
c = 0
#创建一组元音
s="aeiouAEIOU"
v = set(s)
#循环遍历字母表
#在给定的字符串中
for alpha in str1:
#如果存在字母表
#在固定元音
if alpha in v:
c = c + 1
print("No. of vowels ::>", c)
#驱动程序代码
str1 = input("Enter the string ::>")
countvowel(str1)输出结果Enter the string ::> pythonprogram No. of vowels ::> 3