Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python | Count the Number of matching characters in a pair of string
Next article icon

We are given astring and our task is to count the number of vowels present in it. Vowels in English include 'a', 'e', 'i', 'o', and 'u' (both uppercase and lowercase). Using sets, we can efficiently check for vowel presence due to their fast membership lookup.For example, if the input string is "Beautiful Day" then the output should be 6 as the vowels present are 'e', 'a', 'u', 'i', 'a', and 'y'.

Using a Set for Fast Lookup

Aset allows quick membership testing, making it an efficient way to count vowels. We iterate through the string and check if each character is in the set of vowels.

Python
s="Python Programming"vowels={'a','e','i','o','u','A','E','I','O','U'}c=sum(1forchinsifchinvowels)print("Number of vowels:",c)

Output
Number of vowels: 4

Explanation:

  • We define a set of vowels.
  • We iterate over the string and count characters that are present in the vowel set.
  • sum(1 for char in s if char in vowels) ensures we get the total vowel count.

Using a Set and Intersection

Instead of iterating through the string, we use set intersection to find common elements between the string and the vowel set.

Python
s="Set operations in Python"vowels={'a','e','i','o','u','A','E','I','O','U'}c=sum(s.count(v)forvinset(s)&vowels)print("Number of vowels:",c)

Output
Number of vowels: 8

Explanation:

  • set(s) & vowels extracts unique vowels from the string.
  • sum(s.count(v) for v in set(s) & vowels) counts occurrences of each vowel in the string.

Count number of vowels using sets in given string

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp