Last Updated : 03 Mar, 2025
We are given a string 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 LookupA set 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(1 for ch in s if ch in vowels)
print("Number of vowels:", c)
Number of vowels: 4
Explanation:
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) for v in set(s) & vowels)
print("Number of vowels:", c)
Number of vowels: 8
Explanation:
Count number of vowels using sets in given string
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4