Reputation:
I have to get count of consonants present in given string but seems like something missing. What do I need to modify to get the expected result?
My code :
var = 'aaeouAIyuiodffgXUEEE'
vowels='aeiou'
for i in vowels:
if i is not var:
print(var)
Expected result:
y 1
d 1
f 2
g 1
x 1
Upvotes: 0
Views: 1007
Reputation: 118
If you want to achieve the same output without any module, we can use LIST to generate similar outcome.
var = 'aaeouAIyuiodffgXUEEE'
vowels='aeiou'
l = []
for i in var.lower():
if i not in vowels:
l.append(i)
for i in sorted(set(l)):
print(i, l.count(i))
output:
d 1
f 2
g 1
x 1
y 1
To know the total consonants, use "sum(l)"
Upvotes: 0
Reputation:
You can use collections.Counter
for this job. It's a dict
subclass where each element is stored as dictionary keys and their counts are stored as dictionary values. So you can access the counts like:
>>> counts['y']
1
Then use sorted
function on tuples of key-value pairs to sort the letters by alphabetical order and use dict
constructor to re-construct the dictionary.
from collections import Counter
var = 'aaeouAIyuiodffgXUEEE'
vowels='aeiou'
counts = Counter([x for x in var.lower() if x not in vowels])
counts = dict(sorted(counts.items()))
Output:
{'d': 1, 'f': 2, 'g': 1, 'x': 1, 'y': 1}
You can find the sum of all consonants by:
total = sum(counts.values())
Output:
6
Upvotes: 3
Reputation: 1216
You should use an iterator i
to navigate through the whole string var
, character by character, and check for each character if it is a constant (or not).
Using a vowels
string is very helpful, and you should check if at least one of the characters in it is equal to i
. Python has already a function for that.
Something like that:
for i in var:
if i not in vowels:
# increase the consonant counter
How to increase the consonant counter? Well, you could use a dictionary that uses consonants as keys. For example:
cons = {'b': 0, 'c': 0, ...}
Don't forget to set all the values to 0 first. You could also create the dictionary using a for
loop (if you want to do it faster and more efficient).
Now, whenever you find a consonant, just do cons[i] = cons[i]+1
.
In the end, iterate through the dictionary and output every key, together with their values.
Upvotes: 0