jupiter notebook

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

Here is a Python function that counts vowels uniquely in a string, meaning it will count each

vowel only once, regardless of how many times it appears in the string:

def count_unique_vowels(s):
"""
Count the number of unique vowels in a string.

Args:
s (str): The input string.

Returns:
int: The number of unique vowels in the string.
"""
# Convert the string to lowercase to handle case-insensitivity
s = s.lower()

# Define the set of vowels


vowels = {'a', 'e', 'i', 'o', 'u'}

# Use a set to collect unique vowels in the string


unique_vowels = set(char for char in s if char in vowels)

# Return the number of unique vowels


return len(unique_vowels)

# Example usage
string = "Hello, World!"
result = count_unique_vowels(string)
print(f"Number of unique vowels in '{string}': {result}")

How It Works:

1. Convert to lowercase: This ensures case-insensitivity (e.g., 'A' and 'a' are treated the
same).
2. Set of vowels: The vowels set contains all English vowels.
3. Filter vowels: The set comprehension extracts only the vowels from the string,
automatically handling duplicates by using a set.
4. Count unique vowels: The length of the unique_vowels set gives the number of unique
vowels.

Example Outputs:
count_unique_vowels("Hello, World!") # Output: 2 ('e', 'o')
count_unique_vowels("Programming") # Output: 1 ('o')
count_unique_vowels("AEIOUaeiou") # Output: 5 ('a', 'e', 'i', 'o', 'u')
count_unique_vowels("xyz") # Output: 0

This function is efficient and works well for any string input!

You might also like