user3186725
user3186725

Reputation: 21

how do i sort a list using count of vowels tried this ..but isnt going right

def conut(words):
    vowels = "aeiou"
    s= 0
    for a in words[0:5]:
        for x in vowels[0:len(vowels)]:
            s = s + (a.count(x))
words= ["elephant","apple","kat"]
b = words.sort(key = conut(words))

Upvotes: 0

Views: 872

Answers (3)

Andrea de Marco
Andrea de Marco

Reputation: 825

You can use the str.count(sub[, start[, end]]): http://docs.python.org/2/library/stdtypes.html#str.count

def vowelscount(word):
    return sum([word.count(x) for x in 'aeiou'])

test = ['aaa', 'aeiouoiea', 'aiuola']
sorted(test, key=vowelscount)

Upvotes: 1

alvas
alvas

Reputation: 122168

You can use Counter to count the number of char in the strings. and then sum the ones that you're interested in, in this case vowels.

>>> from collections import Counter
>>> def vowelcounts(word):
...     vowels = "aeiou"
...     return sum([j for i,j in Counter(word).items() if i in vowels])
... 
>>> test = ["aeaeaeaeaeaeae","ace","aeiouios"]
>>> sorted(test, key=vowelcounts)
['ace', 'aeiouios', 'aeaeaeaeaeaeae']

Upvotes: 0

shuttle87
shuttle87

Reputation: 15934

You want to use sorted with a custom comparison:

def num_vowels(word):
     count = 0
     for c in word:
         if c in "aeiou":
             count += 1
     return count

>>>> test = ["aeaeaeaeaeaeae","ace","aeiouios"]
>>>> sorted(test, key=num_vowels)
['ace', 'aeiouios', 'aeaeaeaeaeaeae']

Upvotes: 0

Related Questions