'How can I make a function that prints the number of unique vowels in a string?
I am creating a program that prints the number of unique vowels in a string, whether upper or lower case. For example: "swEet” would print 1. What I have so far prints the number of vowels but not unique ones. What can I change or add to my code to do this? Thank you. I'm a beginner in Python and coding.
import sys
def count_vowels(sys_str):
sys_str = sys.argv[1].upper()
vowels = 'aeiou'
count = len([c for c in sys_str.lower() if c in
vowels])
return count
sys_str = sys.argv[1].upper()
count = count_vowels(sys_str)
print(count)
Source: DBrowne's answer at Counting the number of vowels in a string using for loops in Python I got some of my code from this user in this question.
Solution 1:[1]
First off
Eatactually has 2 vowels "E" and "a".Second You won't need to use the sys module
You can simplify your code to this if you're just trying to find the vowels in a string:
def count_vowels(sys_str): vowels = 'aeiou' count = len([c for c in sys_str.lower() if c in vowels]) return countAs for finding unique vowels you can write something like this:
def count_vowels(string):
vowels = 'aeiou'
hashmap = {}
array = []
for i, c in enumerate(string.lower()):
if c not in hashmap:
array.append(c)
hashmap[c] = i
else:
array.pop(hashmap[c])
return len(array)
Example:
count_vowels('Eeat')
Output: 1 #<- This is because there are 2 e's now so a is the only unique vowel
- Obviously, there's a lot more efficient time and space solution out there. This is just something off the top of my head. Hopes This helps!
Solution 2:[2]
Is there a requirement that you use for loops? The set type is much better suited to this type of problem -- no iteration necessary (at least in Python, there's obviously still iteration on the back end in C).
VOWELS = set("aeiou")
def count_vowels(s: str) -> int:
return len(VOWELS.intersection(s.lower()))
Examples:
In [6]: count_vowels("Eat")
Out[6]: 2
In [7]: count_vowels("sweEt")
Out[7]: 1
In [8]: count_vowels("hello")
Out[8]: 2
In [9]: count_vowels("aeiou")
Out[9]: 5
In [10]: count_vowels("aeiou"*10)
Out[10]: 5
In [11]: count_vowels("")
Out[11]: 0
In [12]: count_vowels("syzygy")
Out[12]: 0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lenny T. |
| Solution 2 |
