Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i get count of consonants

I have to get count of consonants present in given string
but seems like something missing. What 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

y 1
d 1
f 2
g 1
x 1

>Solution :

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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading